第一个自己完成的leetcode( JAVA) Implement Queue using Stacks

来源:互联网 发布:约瑟夫环算法 数组 编辑:程序博客网 时间:2024/04/30 13:54

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.

代码如下:

class MyQueue {
 Stack<Integer> inbox=new Stack<Integer>();
 Stack<Integer> outbox=new Stack<Integer>();
    // Push element x to the back of queue.
    public void push(int x) {
         inbox.push(x);
    }

    // Removes the element from in front of queue.
    public void pop() {
         while(!inbox.empty()){
          outbox.push(inbox.pop());
         }
       
        outbox.pop();
        while(!outbox.empty()){
         inbox.push(outbox.pop());
        }
       
    }

    // Get the front element.
    public int peek() {
     
         while(!inbox.isEmpty()){
          outbox.push(inbox.pop());
         }
            
        int temp=outbox.peek();
        while(!outbox.isEmpty()){
         inbox.push(outbox.pop());
        }
        return temp;
       
    }

    // Return whether the queue is empty.
    public boolean empty() {
     return inbox.isEmpty();
    }
}


0 0
原创粉丝点击