Implement Queue using Stacks
Implement the following operations of a queue using stacks.
Notes:
push to top, peek/pop from top, size, and is empty operations are valid.解題思路:
用兩個棧來模擬隊列。其中一個棧做緩存之用,另外一個棧只接受。push操作,直接放入接收之棧中。pop操作,若緩存棧存在數據,則從緩存棧中彈出。若緩存棧為空,則將接收棧的數據彈出並插入到緩存棧中,再從緩存棧中彈出。peek操作與pop操作類似。當且僅當兩個棧都為空時,empty才返回true。
class Queue {
public:
// Push element x to the back of queue.
void push(int x) {
stacks[0].push(x);
}
// Removes the element from in front of queue.
void pop(void) {
if(stacks[1].empty()){
while(!stacks[0].empty()){
stacks[1].push(stacks[0].top());
stacks[0].pop();
}
}
stacks[1].pop();
}
// Get the front element.
int peek(void) {
if(stacks[1].empty()){
while(!stacks[0].empty()){
stacks[1].push(stacks[0].top());
stacks[0].pop();
}
}
return stacks[1].top();
}
// Return whether the queue is empty.
bool empty(void) {
return stacks[0].empty() && stacks[1].empty();
}
private:
stack stacks[2];
};
版權聲明:本文為博主原創文章,未經博主允許不得轉載。