232. Implement Queue using Stacks

来源:互联网 发布:网络培训机构 编辑:程序博客网 时间:2024/04/19 06:53

题目

Implement the following operations of a queue using stacks.

  • push(x) -- Push element x to the back of queue.
  • pop() -- Removes the element from in front of queue.
  • peek() -- Get the front element.
  • empty() -- Return whether the queue is empty.
Notes:
  • You must use only standard operations of a stack -- which means only push to toppeek/pop from topsize, and is empty operations are valid.
  • Depending on your language, stack may not be supported natively. You may simulate a stack by using a list or deque (double-ended queue), as long as you use only standard operations of a stack.
  • You may assume that all operations are valid (for example, no pop or peek operations will be called on an empty queue).
分析

只能用栈的基本操作来模拟队列的基本操作,定义两个栈a和b,其中a保存队列的正序,在进队时使用;b保存队列的倒序,在出队时使用。

class Queue {private:    stack<int> a,b;//压入时用a,弹出时用bpublic:// Push element x to the back of queue.void push(int x) {    if (b.empty()) a.push(x);//b为空时证明没有pop过,直接在a中压入x    else {        while (!b.empty()){//如果队列进行过pop操作,则b保存的是pop之后的队列,是队列倒序            a.push(b.top());//因此a在压入新元素的时候先将b压入a,在a中形成正序队列,再压入x            b.pop();        }        a.push(x);    }}// Removes the element from in front of queue.void pop(void) {    if (a.empty()) b.pop();//a为空证明没有再压入新元素,b已经是队列倒序,可以直接弹出    else{        while(!a.empty()){//否则b保存a的倒序结果,然后弹出            b.push(a.top());            a.pop();        }        b.pop();    }}// Get the front element.int peek(void) {    if (a.empty()) return b.top();//a为空则与pop一样返回b的首元素    else {        while(!a.empty()){//否则b保存a的倒序结果,然后弹出b的首元素            b.push(a.top());            a.pop();        }        return b.top();    }}// Return whether the queue is empty.bool empty(void) {    return a.empty()&&b.empty();}};


0 0
原创粉丝点击