Implement Queue by Two Stacks

本文介绍了一种使用两个栈来实现队列的方法。通过在两个栈之间转移元素,可以实现在队列尾部添加元素(push),从队列头部移除元素(pop)并返回其值,以及查看队列头部元素(top)的功能。

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.


分析

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




转载于:https://www.cnblogs.com/zhxshseu/p/9415037aea8647d4817529ba5f792bde.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值