Stack&Queue
ZSISC 32nd 鄭云晶
stack
- 資料結構 (LIFO)
- 後進先出(Last In First Out)
- 需引入函式庫<stack>
queue
- 資料結構 (FIFO)
- 先進先出(First In First Out)
- 需引入函式庫<queue>
堆疊
佇列


| push(x) | push(x) | 放入元素 |
| pop() | pop() | 移除前端元素 |
| top() | front() | 取得頂端/前端元素 |
| empty() | empty() | 是否為空 |
| size() | size() | 元素數量 |
| X | back() | 取得尾端元素 |
stack
queue
常用函式
宣告: stack/queue <型態> 名稱;
宣告
Stack
Queue
stack<int> s; queue<int> q;push
Stack
Queue
1
1
s.push(1)
q.push(1)
push
Stack
Queue
1
1
push
Stack
Queue
1
1
2
2
s.push(2)
q.push(2)
push
Stack
Queue
1
1
2
2
push
Stack
Queue
1
1
2
2
3
s.push(3)
q.push(3)
3
push
Stack
Queue
1
1
2
2
3
3
s.top()
q.front()
pop
Stack
Queue
1
1
2
2
3
3
s.pop()
q.pop()
pop
Stack
Queue
1
2
2
3
pop
Stack
Queue
1
2
2
3
q.pop()
s.pop()
pop
Stack
Queue
1
3
pop
Stack
Queue
1
3
q.pop()
s.pop()
pop
Stack
Queue
empty
Stack
Queue
回傳0
回傳1
size
Stack
Queue
回傳3
回傳0
1
2
3
範例
*空的時候不能 pop() 或 top()
#include <iostream>
#include <stack>
using namespace std;
int main(){
stack<int> s;
s.push(10);
s.push(20);
s.push(30);
cout << s.top() << endl;
s.pop();
cout << s.top() << endl;
}#include <iostream>
#include <queue>
using namespace std;
int main(){
queue<int> q;
q.push(10);
q.push(20);
q.push(30);
cout << q.front() << endl;
q.pop();
cout << q.front() << endl;
}10
20
30
20
q&p的邂逅
kahoot
Minimal
By shiny0515
Minimal
- 1