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

原创 2015年07月08日 09:51:38

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();
    }
}



LeetCode232 Implement Queue using Stacks Java 题解

题目: Implement the following operations of a queue using stacks. push(x) -- Push element x to...

【leetcode】232. Implement Queue using Stacks

一、题目描述 Implement the following operations of a queue using stacks. push(x) -- Push element x...

LeetCode:Implement Queue using Stacks

LeetCode:Implement Queue using Stacks1、题目: Implement the following operations of a queue using stac...
  • BestZem
  • BestZem
  • 2016年07月16日 22:08
  • 177

LeetCode232—Implement Queue using Stacks

LeetCode232: Implement Queue using Stacks

LeetCode Implement Queue using Stacks

题目: Implement the following operations of a queue using stacks. push(x) -- Push element x to...

LeetCode 232 Implement Queue using Stacks(用栈来实现队列)(*)

翻译用栈来实现队列的下列操作。push(x) —— 将元素x写入到队列的尾部 pop() —— 从队列首部移除元素 peek() —— 返回队列首部元素 empty() —— 返回队列是否为空注意:你...
  • NoMasp
  • NoMasp
  • 2016年01月20日 21:18
  • 2477

[leetcode] Implement Queue using Stacks

题目链接在此。 Implement the following operations of a queue using stacks. push(x) -- Push element x t...

[leetcode: Python]232. Implement Queue using Stacks

题目: Implement the following operations of a queue using stacks.push(x) – Push element x to the back...
  • NXHYD
  • NXHYD
  • 2017年05月12日 13:09
  • 158

[LeetCode]232.Implement Queue using Stacks

题目Implement the following operations of a queue using stacks.push(x) – Push element x to the back of...

[leetcode] 232. Implement Queue using Stacks

Implement the following operations of a queue using stacks. push(x) -- Push element x to the back o...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:第一个自己完成的leetcode( JAVA) Implement Queue using Stacks
举报原因:
原因补充:

(最多只允许输入30个字)