首页 > 代码库 > LeetCode 232 Implement Queue using Stacks

LeetCode 232 Implement Queue using Stacks

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

 

思路:

利用两个栈,每次入队的操作时,将一个栈中的元素全部弹出,后在有元素的栈中压入入队元素,后将该栈的全部元素弹出,压回第一个栈中即可。

 

解法:

 1 import java.util.Stack; 2  3 public class MyQueue 4 { 5     private Stack<Integer> inputStack; 6     private Stack<Integer> outputStack; 7  8     public MyQueue() 9     {10         inputStack = new Stack<>();11         outputStack = new Stack<>();12     }13 14     public void push(int x)15     {16         while(!outputStack.isEmpty())17             inputStack.push(outputStack.pop());18         inputStack.push(x);19         while(!inputStack.isEmpty())20             outputStack.push(inputStack.pop());21     }22 23     public void pop()24     { outputStack.pop(); }25 26     public int peek()27     { return outputStack.peek(); }28 29     public boolean empty()30     { return outputStack.isEmpty(); }31 }

 

LeetCode 232 Implement Queue using Stacks