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

在上国外某教授的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
  	 */
}

猜你喜欢

转载自blog.csdn.net/shendezhuti/article/details/78326489
今日推荐