i213. stack 練習
i213. stack 練習
| 解題思路 : stack的基本運用
<stack的宣告>
stack<int> stk; 整數stack
stack<char> stk; 字元stack
stack<double> stk; 浮點數stack
<stack基本語法>
stk.top(); 取出stack中最上層的數
stk.pop(); 刪除stack中最上層的數
stk.push(x); 將x加入stack中
stk.empty(); 若stack是空的回傳true,否則回傳false
|
程式碼 :
/*
i213. stack 練習
https://zerojudge.tw/ShowProblem?problemid=i213
skyblue
AC (17ms, 416KB)
*/
#include <bits/stdc++.h>
using namespace std;
int main(){
int n;
scanf("%d", &n);
stack<int> stk;
while(n--){
int k;
scanf("%d", &k);
switch (k){
case 1:
int x;
scanf("%d", &x);
stk.push(x);
break;
//若k=1,將x加入stack
case 2:
if(stk.empty()) printf("-1\n");
else printf("%d\n", stk.top());
break;
//若k=2且stack是空的,輸出-1;若不是空的,輸出最上層的數
case 3:
if(!stk.empty()){
stk.pop();
break;
}
//若k=3且stack不是空的,刪除最上層的數
}
}
return 0;
}
留言
張貼留言