标签:列表 move stack empty ble struct removes port oid
Implement the following operations of a queue using stacks.
使用堆栈实现队列的以下操作。
Example:
MyQueue queue = new MyQueue(); queue.push(1); queue.push(2); queue.peek(); // returns 1 queue.pop(); // returns 1 queue.empty(); // returns false
Notes:
push to top
, peek/pop from top
, size
, and is empty
operations are valid.您必须仅使用一个堆栈的标准操作 - 这意味着只能从顶部切换到顶部,查看/弹出,大小,并且空操作是有效的。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
标签:列表 move stack empty ble struct removes port oid
原文地址:https://www.cnblogs.com/chanaichao/p/9343791.html