[Data Structure Notes] Stack (array simulation stack, monotonic stack)

 Some notes on learning data structures on Acwing


Stack: Follow the "last in, first out" principle. That is, the last element pushed onto the stack will be popped first.

Use an array to simulate a stack: The simulated stack includes two basic operations, insertion and popping, which are reflected in the code. Every time an element is pushed onto the stack, a pointer to the top of the stack is It will then move back to point to the newly added element. Next is a demonstration of how to use an array to simulate a stack.

#include<iostream>
using namespace std;
const int N = 1e6 + 10;
int tt = -1, m; //tt表示栈顶索引,初始化为-1
int stack[N];

void push(int x) 
{
    stack[++ tt] = x; //栈顶所在索引往后移一格,放入x
}

void pop() 
{
    -- tt; //弹出栈顶元素,tt往前移
}

bool isEmpty() //创建bool数组,判断栈是否为空
{ 
    if (tt == -1) return true;
    else return false;
}

int query() 
{
    return stack[tt]; //返回栈顶元素
}

int main() 
{
    int x;
    cin >> m;
    string op;
    while (m--) {
        cin >> op;
        if (op == "push") 
        {
            cin >> x;
            push(x);
        }
        else if (op == "query") 
        {
            cout<<query()<<endl;
        }
        else if (op == "pop") 
        {
            pop();
        }
        else if (op == "empty") 
        {
            if (isEmpty()) 
            {
                cout << "YES";
            }
            else 
            {
                cout << "NO";
            }
            cout << endl;
        }
    }
    return 0;
}

monotonic stack

Implementation idea: Create a strictly monotonically increasing stack. That is to say, each input number needs to be judged. If the number x to be added is less than or equal to the top element of the stack at this time, that is, stk[tt] >= x, then the top element of the stack cannot be the answer. It pops up. And if the number x to be added is greater than the top element of the stack at this time, that is, stk[tt] <

#include <iostream>
using namespace std;

const int N = 100010;
int stk[N], tt, n;

int main()
{
    cin>>n;
    while (n --)
    {
        int x;
        cin>>x;
        while(tt && stk[tt] >= x) tt --; //如果栈不会空,且加入的数小于等于栈顶元素,则栈顶元素出栈。
        if(!tt) cout<<-1<<' '; //如果栈为空,即没有答案,输出-1
        else cout<<stk[tt]<<' ';
        stk[++tt] = x; //将栈顶索引前移,并放入x
    }
}

Guess you like

Origin blog.csdn.net/Radein/article/details/134701151