数组模拟栈



原题链接

题意是用数组模拟一个栈,支持四种栈操作:在栈顶插入元素,弹出栈顶元素,查询栈顶元素,查询栈是否为空。

用数组模拟栈只需要开一个数组存储栈元素,再用一个额外的变量top表示当前栈顶元素下标。

直接看代码吧:

#include<bits/stdc++.h>
using namespace std;

const int N = 1e5 + 5;
int stk[N], top;            //栈数组和栈顶下标

void init() {
    top = 0;               //初始时top为0,表示栈内没有元素
}

void Push(int x) {
    stk[++top] = x;        //栈顶压入一个元素,top指针加一,并指向新加入的元素x
}

int Query() {
    return stk[top];       //返回栈顶元素
}

void Pop() {
    --top;                 //栈顶指针减一,表示将栈顶元素弹出
}

string Empty() {
    return top > 0 ? "NO" : "YES";    //top为零则栈空,top大于零则栈不空
}


int main() {
    int M;
    cin >> M;
    init();
    while(M--) {
        string op;
        int x;
        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") {
            cout << Empty() << endl;
        }
    }
}

原文地址:https://www.cnblogs.com/linrj/p/13322157.html