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.

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

使用两个栈,一个输入栈,一个输出栈

输入O(1),输出O(n)

 1 class MyQueue {//栈 队列 my
 2     Stack<Integer> stack1;
 3     Stack<Integer> stack2;
 4 
 5     /** Initialize your data structure here. */
 6     public MyQueue() {
 7         stack1 = new Stack<Integer>();
 8         stack2= new Stack<Integer>();
 9     }
10     
11     /** Push element x to the back of queue. */
12     public void push(int x) {
13         stack1.push(x);
14     }
15     
16     /** Removes the element from in front of queue and returns that element. */
17     public int pop() {
18         if(stack2.isEmpty()){
19             while(!stack1.isEmpty()){
20                 Integer x = stack1.pop();
21                 stack2.push(x);
22             }
23         }
24         return stack2.pop();
25     }
26     
27     /** Get the front element. */
28     public int peek() {
29         if(stack2.isEmpty()){
30             while(!stack1.isEmpty()){
31                 Integer x = stack1.pop();
32                 stack2.push(x);
33             }
34         }
35         return stack2.peek();
36     }
37     
38     /** Returns whether the queue is empty. */
39     public boolean empty() {
40         return stack2.isEmpty()&&stack1.isEmpty();
41     }
42 }

 

相关题

使用队列实现栈 LeetCode225 https://www.cnblogs.com/zhacai/p/10565181.html

posted @ 2019-03-20 15:20  月半榨菜  阅读(130)  评论(0编辑  收藏  举报