文章目錄
- 用棧實作隊列
-
- 題目描述
- 具體代碼
用棧實作隊列
題目描述
請你僅使用兩個棧實作先入先出隊列。隊列應當支援一般隊列支援的所有操作(push、pop、peek、empty):
實作 MyQueue 類:
void push(int x) 将元素 x 推到隊列的末尾
int pop() 從隊列的開頭移除并傳回元素
int peek() 傳回隊列開頭的元素
boolean empty() 如果隊列為空,傳回 true ;否則,傳回 false
具體代碼
代碼如下(示例):
class MyQueue {
public:
stack<int> stack1,stack2;
/** Initialize your data structure here. */
MyQueue() {
}
/** Push element x to the back of queue. */
void push(int x) {
stack1.push(x);
}
/** Removes the element from in front of queue and returns that element. */
int pop() {
if (stack2.empty()){
while (!stack1.empty()){
int tem = stack1.top();
stack1.pop();
stack2.push(tem);
}
}
int front = stack2.top();
stack2.pop();
return front;
}
/** Get the front element. */
int peek() {
if (stack2.empty()){
while (!stack1.empty()){
int tem = stack1.top();
stack1.pop();
stack2.push(tem);
}
}
return stack2.top();
}
/** Returns whether the queue is empty. */
bool empty() {
return stack1.empty() && stack2.empty();
}
};