LintCode-Implement Queue by Stacks

使用两个栈实现队列操作
本文介绍如何仅使用两个栈来实现队列的基本操作,包括压栈、弹栈和查看队首元素,并确保所有操作的平均时间复杂度为O(1)。

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

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

Challenge

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 public class Solution {
 2     private Stack<Integer> stack1;
 3     private Stack<Integer> stack2;
 4 
 5     public Solution() {
 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     private void shuffle(){
15         while (!stack2.isEmpty())
16             stack1.push(stack2.pop());
17     }
18 
19     public int pop() {
20         if (stack1.isEmpty()) shuffle();
21         return stack1.pop();
22     }
23 
24     public int top() {
25         if (stack1.isEmpty()) shuffle();
26         return stack1.peek();
27     }
28 }

 

转载于:https://www.cnblogs.com/lishiblog/p/4196912.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值