关闭

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

标签: javaclassleetcode
211人阅读 评论(0) 收藏 举报
分类:

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

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:3636次
    • 积分:106
    • 等级:
    • 排名:千里之外
    • 原创:7篇
    • 转载:1篇
    • 译文:0篇
    • 评论:0条
    文章存档