Lintcode: Implement Queue by Stacks 解题报告

本文介绍了一种使用两个栈来高效实现队列的方法。通过在两个栈之间转移元素,可以确保队列的基本操作如push、pop和top在平均情况下达到O(1)的时间复杂度。文章提供了详细的算法步骤及代码实现。

Implement Queue by Stacks

原题链接 : http://lintcode.com/zh-cn/problem/implement-queue-by-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.

样例

For push(1), pop(), push(2), push(3), top(), pop(), you should return 1, 2 and 2

挑战

implement it by two stacks, do not use any other data structure and push, pop and top should be O(1) by AVERAGE.

SOLUTION 1:

使用两个栈,stack1和stack2。

http://www.ninechapter.com/problem/49/

对于Queue的操作对应如下:

 

 

Queue.Push:

 

    push到Stack1

 

 

 

Queue.Pop:

 

    如果Stack2非空,Stack2.pop

 

    否则将Stack1中的所有数pop到Stack2中(相当于顺序颠倒了放入),然后Stack2.pop()

 

 

 

每个数进出Stack1和Stack2各1次,所以两个操作的均摊复杂度均为O(1)

 

 

 1 public class Solution {
 2     private Stack<Integer> stack1;
 3     private Stack<Integer> stack2;
 4 
 5     public Solution() {
 6        // do initialization if necessary
 7        stack1 = new Stack<Integer>();
 8        stack2 = new Stack<Integer>();
 9     }
10     
11     public void push(int element) {
12         // write your code here
13         stack1.push(element);
14     }
15 
16     public int pop() {
17         // write your code here
18         if (stack2.isEmpty()) {
19             while (!stack1.isEmpty()) {
20                 stack2.push(stack1.pop());
21             }
22         }
23         
24         return stack2.pop();
25     }
26 
27     public int top() {
28         // write your code here
29         // write your code here
30         if (stack2.isEmpty()) {
31             while (!stack1.isEmpty()) {
32                 stack2.push(stack1.pop());
33             }
34         }
35         
36         return stack2.peek();
37     }
38 }
View Code

 

GITHUB:

https://github.com/yuzhangcmu/LeetCode_algorithm/blob/master/lintcode/stack/StackQueue.java

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值