题目解析
题目要求我们用栈来实现队列的基本操作:push(),pop(),peek()和empty()。
思路
做题目前得先了解栈的基本找操作,为了实现队列的操作,我使用了两个栈来模拟队列。
要放如元素时,直接把元素放进栈a中,
要删除元素时,首先判断栈a是否时空的,诺不是,在判断栈b是否有元素,如果同时满足栈a不空且栈b为空则将栈a的源素从栈顶开始搬进栈b,在删除b的栈顶元素。反之则直接删除栈b的栈顶元素。
查找队列头元素时与删除同理。
判断队列是否为空时,之需先判断栈a和b是否为空,时则返回true否则返回false。
代码
class MyQueue {
stack<int> a;
stack<int> b;
public:
/** Initialize your data structure here. */
MyQueue() {
}
/** Push element x to the back of queue. */
void push(int x) {
a.push(x);
}
/** Removes the element from in front of queue and returns that element. */
int pop() {
int i;
if(a.empty()==false&&b.empty()==true){
while(a.empty()==false){
i=a.top();
a.pop();
b.push(i);
}
}
i=b.top();
b.pop();
return i;
}
/** Get the front element. */
int peek() {
int i;
if(a.empty()==false&&b.empty()==true){
while(a.empty()==false){
i=a.top();
a.pop();
b.push(i);
}
}
return b.top();
}
/** Returns whether the queue is empty. */
bool empty() {
if(a.empty()==false){
return false;
}
if(b.empty()==false){
return false;
}
else
return true;
}
};
结果
小结
首先要对栈有所了解,同过两个栈来模拟队列的想法还是比较容易想到的,在完成代码时需要考虑什么时候将a中的元素搬进b里,明白了这个其他就没什么难度了。