leetcode oj java Implement Queue using Stacks

来源:互联网 发布:四川移动网络加速器 编辑:程序博客网 时间:2024/05/17 21:39

一、问题描述:

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).

二、思路:

      两个栈存放数据。ST1  ST2

    在放入数据(push)的时候压入栈1,

弹出数据的时候,如果栈2不为空,以此弹出栈1中的数据压入栈2,取栈2的最上边的数据

获得最前边的数据的时候,如果栈2不为空,以此弹出栈1中的数据压入栈2,取栈2的最上边的数据。


举例: push(1) , push(2) , pop() , push(3) , peek(),  push(4), pop() , pop()

push(1)   :  栈1的状态是 1   栈2是 null

push(2)  :  栈1的状态是 1 2   栈2是 null

pop()      :  栈1的状态是 null    栈2首先是 2 1 其次弹出1

push(3)   :  栈1的状态是3 栈2是2

peek(3)   :  栈1的状态是3 栈2是2 取出2

push(4)   :  栈1的状态是3  4 ,  栈2是2

pop():          栈1的状态是3  4 ,  栈2是null  

pop():          栈1的状态是null ,  栈2是4 3 其次弹出3


三、代码

class MyQueue {       Stack<Integer> st1 = new Stack<Integer>();    Stack<Integer> st2 = new Stack<Integer>();    public void push(int x) {        st1.push(x);    }    // Removes the element from in front of queue.    public void pop() {         if(!st2.empty()){            st2.pop();            return ;        }        while(!st1.empty()){            int tmp = st1.peek();            st1.pop();            st2.push(tmp);        }        st2.pop();    }    // Get the front element.    public int peek() {         if(!st2.empty()){            return st2.peek();        }        while(!st1.empty()){            int tmp = st1.peek();            st1.pop();            st2.push(tmp);        }        return st2.peek();    }    // Return whether the queue is empty.    public boolean empty() {        return st1.empty() && st2.empty();    }}


0 0
原创粉丝点击