Implement queue with two stack 用两个堆实现队列

本文介绍了如何利用两个堆来实现一个队列,确保每个队列操作的平均成本为常数级别的堆操作。进队操作将元素推入inbox,而出队操作则检查outbox,若为空则将inbox元素弹出并推入outbox,否则直接从outbox弹出元素。给出了具体的Java代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在上国外某教授的algorithm课,课后有一个小quiz,问题如下

 Implement a queue with two stacks so that each queue operations takes a constant amortized number of stack operations.

用两个堆实现一个队列,这个队列每次操作的消耗应该是堆操作的分期常量。

我们知道队列里的元素满足先进先出的原则,而堆里面的元素满足后进先出原则。那么我们可以这么来做:

如果我们把这个俩个堆分为inbox 和outbox 

  进队(enqueue)

       我们把元素push放入inbox


  出队(dequeue)

发现如果outbox是empty的,我们把inbox里面的元素pop拿出来并且push放入outbox中

发现outbox不为空,则就将outbox里面的元素pop返回拿出来


java代码如下

 

public class QueueWithTwoStack {
  private Stack inbox=new Stack();
  private Stack outbox=new Stack();
  
  	public void enqueue(T item){
  		inbox.push(item);
  	}
  
  	public T dequeue(){
  		if(outbox.isEmpty()){
  			while(!inbox.isEmpty()){
  				outbox.push(inbox.pop());
  			}
  		}
  		
  		return outbox.pop();
  	}
  
  	
  	public static void main(String args[]){
  		QueueWithTwoStack test=new QueueWithTwoStack<>();
  		for (int i=0;i<5;i++){
  		test.enqueue(i);
  		}
  		
  		for (int i=0;i<5;i++){
  		int j=	test.dequeue();
  		System.out.println(j);
  		}
  	}
  	/**output:
  	 * 0
  	 * 1
  	 * 2
  	 * 3
  	 * 4
  	 */
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值