1. 程式人生 > >126. Implement Queue using Stacks

126. Implement Queue using Stacks

返回 col lan win nat 雙端 是否為空 peek 切換

題目:

Implement the following operations of a queue using stacks.

使用堆棧實現隊列的以下操作。

  • push(x) -- Push element x to the back of queue. 將元素x推送到隊列的後面。
  • pop() -- Removes the element from in front of queue.從隊列前面刪除元素。
  • peek() -- Get the front element.獲取前面的元素。
  • empty() -- Return whether the queue is empty. 返回隊列是否為空。

Example:

MyQueue queue = new MyQueue();

queue.push(1);
queue.push(2);  
queue.peek();  // returns 1
queue.pop();   // returns 1
queue.empty(); // returns false

Notes:

  • You must use only standard operations of a stack -- which means only push to top, peek/pop from top, size, and is emptyoperations 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).您可以假設所有操作都是有效的(例如,不會在空隊列上調用pop或Peek操作)。

解答:

 1 class MyQueue {
 2     
 3     private Stack<Integer> input;
 4     private Stack<Integer> output;
 5     
 6     /** Initialize your data structure here. */
 7     public MyQueue() {
 8         input = new Stack<>();
 9         output = new Stack<>();
10     }
11     
12     /** Push element x to the back of queue. */
13     public void push(int x) {
14         input.push(x);
15     }
16     
17     /** Removes the element from in front of queue and returns that element. */
18     public int pop() {
19         move();
20         return output.pop();
21     }
22     
23     /** Get the front element. */
24     public int peek() {
25         move();
26         return output.peek();
27     }
28     
29     /** Returns whether the queue is empty. */
30     public boolean empty() {
31         return input.isEmpty()&&output.isEmpty();
32     }
33     
34     private void move() {
35         if (output.isEmpty())
36             while (!input.isEmpty()) 
37                 output.push(input.pop());
38     }
39 }
40 
41 /**
42  * Your MyQueue object will be instantiated and called as such:
43  * MyQueue obj = new MyQueue();
44  * obj.push(x);
45  * int param_2 = obj.pop();
46  * int param_3 = obj.peek();
47  * boolean param_4 = obj.empty();
48  */

詳解:

1.隊列:先進先出。 棧:先進後出

2.對於四個方法,隊列的push和empty方法與棧相同,只是棧的pop和peek是針對隊尾元素,而隊列的pop和peek是針對隊首元素

126. Implement Queue using Stacks