题目:
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
, andis 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).您可以假设所有操作都是有效的(例如,不会在空队列上调用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是针对队首元素
原文地址:https://www.cnblogs.com/chanaichao/p/9343791.html
时间: 2024-10-13 19:24:03