Lintcode40-Implement Queue by Two Stacks-Medium

40. Implement Queue by Two Stacks

As the title described, you should only use two stacks to implement a queue's actions.

The queue should support push(element)pop() and top() where pop is pop the first(a.k.a front) element in the queue.

Both pop and top methods should return the value of first element.

Example

Input
push(1)
push(2)
push(3)
push(4)
push(5)
pop()
pop()
push(6)
push(7)
push(8)
push(9)
pop()
pop()
Expected
[1,2,3,4]

思路:

用两个stack,实现一个queue。

push到stack2。pop的时候,先判断stack1是否为空:如果不为空(说明上一轮push进stack1的,没有pop完),直接stack1.pop(); 如果为空,则把stack2所有元素全部push到stack1,(保证第一个push到stack2的元素最后push进stack1),再stack1.pop().

 

注意:

  1. 创建两个类变量,在构造方法中初始化两个类变量stack1, stack2.
  2. 代码改进,line 17,18 和 line 26,27 重复,可以封装成一个方法。

代码:

 1 public class MyQueue {
 2     Stack<Integer> stack1;
 3     Stack<Integer> stack2;
 4     
 5     public MyQueue() {
 6         stack1 = new Stack<Integer>();
 7         stack2 = new Stack<Integer>();
 8     }
 9     
10     public void push(int element) {
11         stack2.push(element);
12     }
13 
14     
15     public int pop() {
16         if (stack1.isEmpty()) {
17             while (!stack2.isEmpty()) {
18                 stack1.push(stack2.pop());
19             }
20         }
21         return stack1.pop();
22     }
23 
24     public int top() {
25         if (stack1.isEmpty()) {
26             while (!stack2.isEmpty()) {
27                 stack1.push(stack2.pop());
28             }
29         }
30         return stack1.peek();
31     }
32 }

代码改进:

public class MyQueue {
    Stack<Integer> stack1;
    Stack<Integer> stack2;
    
    public MyQueue() {
        stack1 = new Stack<Integer>();
        stack2 = new Stack<Integer>();
    }
    
    public void stack2ToStack1(){
        while (!stack2.isEmpty()) {
            stack1.push(stack2.pop());
        }
    }
    
    public void push(int element) {
        stack2.push(element);
    }

    
    public int pop() {
        if (stack1.isEmpty()) {
            this.stack2ToStack1();
        }
        return stack1.pop();
    }

    public int top() {
        if (stack1.isEmpty()) {
            this.stack2ToStack1();
        }
        return stack1.peek();
    }
}

 

posted @ 2019-04-03 22:19  IreneZh  阅读(146)  评论(0编辑  收藏  举报