Implement Queue using Stacks

来源:互联网 发布:gogs windows 编辑:程序博客网 时间:2024/05/02 16:23

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 top, peek/pop from top, size, 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).

队列:先进先出。push在队尾,pop在队首,peek在队首。
栈:后进先出。只能对栈顶进行操作。

两种数据结构在逻辑上正好相反,反反得正,所以需要两个栈进行顺序的颠倒。最简单的方法是以栈1作为存储空间,然后每次需要颠倒的时候(pop和peek),都去栈2中颠倒一下然后还原回栈1。毫无疑问,这是一种很烂的算法,因为无论是从时间上,还是空间上,都造成了极大的浪费。我们完全可以把栈1用作入队操作,把栈2用作出队操作。

class MyQueue {    private Stack<Integer> s1;    private Stack<Integer> s2;    public MyQueue() {        // TODO Auto-generated constructor stub        s1 = new Stack<Integer>();        s2 = new Stack<Integer>();    }    // Push element x to the back of queue.    public void push(int x) {        s1.push(x);    }    // Removes the element from in front of queue.    public void pop() {        if(!s2.empty()){            s2.pop();        }        else {            while(!s1.empty()){                s2.push(s1.pop());            }            s2.pop();        }    }    // Get the front element.    public int peek() {        if(!s2.isEmpty()){            return s2.peek();        }        else {            while(!s1.empty()){                s2.push(s1.pop());            }            return s2.peek();        }    }    // Return whether the queue is empty.    public boolean empty() {        return s1.isEmpty() && s2.isEmpty();    }}

简单介绍一下原理:

这里,我把【栈1 pop 一个数,栈2 push 这个数】操作简称为【颠倒】。如果进队顺序是1、2、3、4,那么期望的出队顺序也是1、2、3、4。

  • 操作1:往栈1 push 1、2;颠倒1、2到栈2;push 3、4,颠倒3、4到栈2。栈2从顶部到底部的顺序是1、2、3、4。
  • 操作2:往栈1 push 1、2、3;颠倒1、2、3到栈2; push 4,颠倒4到栈2。栈2从顶部到底部的顺序是1、2、3、4。

不难发现出队操作就是栈2的不断pop,无论操作1,还是操作2,无论push和颠倒的顺序和时机,对出队顺序没有影响。

0 0
原创粉丝点击