Triển khai Stack (LIFO) chỉ dùng Queue (FIFO). Các phương thức: push, pop, top, empty.
Cách đơn giản: dùng deque, push_front/pop_front để mô phỏng stack.
Ví dụ triển khai C++
#include <bits/stdc++.h>
using namespace std;
class MyStack {
deque<int> q;
public:
void push(int x) { q.push_front(x); }
int pop() { int v = q.front(); q.pop_front(); return v; }
int top() { return q.front(); }
bool empty() { return q.empty(); }
};
int main() {
MyStack st;
st.push(10);
st.push(20);
cout << st.pop() << endl; // 20
cout << st.pop() << endl; // 10
return 0;
}
Đầu vào / Đầu ra
Input: push(10), push(20), pop(), pop() Output: 20, 10