AcWing 模擬棧 棧 模擬

2021-09-26 08:52:01 字數 1293 閱讀 4496

時/空限制:1s / 64mb

實現乙個棧,棧初始為空,支援四種操作:

(1) 「push x」 – 向棧頂插入乙個數x;

(2) 「pop」 – 從棧頂彈出乙個數;

(3) 「empty」 – 判斷棧是否為空;

(4) 「query」 – 查詢棧頂元素。

現在要對棧進行m個操作,其中的每個操作3和操作4都要輸出相應的結果。

第一行包含整數m,表示操作次數。

接下來m行,每行包含乙個操作命令,操作命令為」push x」,」pop」,」empty」,」query」中的一種。

對於每個」empty」和」query」操作都要輸出乙個查詢結果,每個結果佔一行。

其中,」empty」操作的查詢結果為「yes」或「no」,」query」操作的查詢結果為乙個整數,表示棧頂元素的值。

1≤m≤100000,

1≤x≤10^9

所有操作保證合法。

10

push 5

query

push 6

popquery

popempty

push 4

query

empty

5

5yes4no

題意:模擬乙個棧,共有四種操作。

思路:直接模擬,寫的是陣列型的,不過操作和指標的類似。

accepted code:

/* 

* @author: lzyws739307453

* @language: c++

*/#include using namespace std;

const int maxn = 100005;

int stack[maxn], top = 0;

void push(int x)

void pop()

bool empty()

int query()

int main()

else if (!strcmp(op, "pop"))

pop();

else if (!strcmp(op, "empty"))

printf(empty() ? "yes\n" : "no\n");

else printf("%d\n", query());

}return 0;

}

AcWing 828 模擬棧(C 演算法)

1 push x 向棧頂插入乙個數x 2 pop 從棧頂彈出乙個數 3 empty 判斷棧是否為空 4 query 查詢棧頂元素。現在要對棧進行m個操作,其中的每個操作3和操作4都要輸出相應的結果。輸入格式 第一行包含整數m,表示操作次數。接下來m行,每行包含乙個操作命令,操作命令為 push x ...

用棧模擬佇列和佇列模擬棧

棧 先進後出 filo 佇列 先進先出 fifo class myqueue 兩棧模擬佇列 def init self self.input self.output 進佇列 defpush self,x 出佇列 defpop self self.peek return self.output.pop...

1140 雞蛋棧 模擬棧

時間限制 1000 ms 記憶體限制 65535 kb 難度 1 描述 繼佇列之後,我們又來學習一種新的資料結構 棧。將佇列的頭部封閉後,就構成了棧這種資料結構,原來佇列頭部就是棧底,原來佇列的尾部就是棧頂。棧與佇列的不同就在於棧的底端是封閉的。所以,棧的插入和刪除操作只能在棧的一端進行,即棧頂。棧...