C++
stack and queue
queue
- 先進先出(FIFO, First-In-
First-Out) - 只允許在後端進行加入操作,在
前端進行取出操作

queue
ZeroJudge e155

透過 modulo (%) 來實現
int q[50];
int head = 0, tail = 0;
int isfull()
{
if((tail + 1) % 50 == head)
return 1;
else
return 0;
}
int isempty()
{
return head == tail;
}
int push(int v)
{
if(isfull())
return 0;
q[tail] = v;
tail = (tail + 1) % 50;
return 1;
}
int pop(int v)
{
if(isempty())
return 0;
q[head] = v;
head = (head + 1) % 50;
return 1;
}
STL: queue
#include <iostream>
#include <queue> // 記得引入
using namespace std;
int main() {
queue<int> q;
// 1. 推入元素 (Push)
q.push(10); // 10 在最前面
q.push(20);
q.push(30);
// 2. 查看隊頭與隊尾
cout << "Front: " << q.front() << endl; // 10
cout << "Back: " << q.back() << endl; // 30
// 3. 移除元素 (Pop)
q.pop(); // 移除 10 (最早進來的)
cout << "Front after pop: " << q.front() << endl; // 20
// 4. 走訪 Queue
cout << "Queue content: ";
while (!q.empty()) {
cout << q.front() << " ";
q.pop();
}
// 輸出: 20 30 (順序是正的)
return 0;
}Stack
- 後進先出(LIFO, Last-In-First-Out)
- 只允許在後端進行加入操作,在後端進行取出操作

STL: stack
#include <iostream>
#include <stack> // 記得引入
using namespace std;
int main() {
stack<int> s;
s.push(10); // 1. 推入元素 (Push)
s.push(20);
s.push(30); // 30 在最上面
// 2. 查看頂端元素 (Top)
cout << "Top element: " << s.top() << endl; // 輸出 30
// 3. 移除元素 (Pop)
s.pop(); // 移除 30
cout << "Top after pop: " << s.top() << endl; // 輸出 20
// 4. 走訪 Stack (標準寫法:一邊看一邊丟)
cout << "Remaining elements: ";
while (!s.empty()) {
cout << s.top() << " ";
s.pop();
}
// 輸出: 20 10 (順序是反的)
return 0;
}練習
Title Text
Subtitle
C++stack and queue
By ernestii26
C++stack and queue
- 18