1. 程式人生 > 實用技巧 >陣列模擬棧

陣列模擬棧



原題連結

題意是用陣列模擬一個棧,支援四種棧操作:在棧頂插入元素,彈出棧頂元素,查詢棧頂元素,查詢棧是否為空。

用陣列模擬棧只需要開一個數組儲存棧元素,再用一個額外的變數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;
        }
    }
}