Cracking coding interview(3.5)使用2个堆栈实现一个队列

3.5 Implement a MyQueue class which implements a queue using two stacks.

explanation:

1.MyQueue实现原理:当MyQueue需要offer(add)一个元素时,直接添加到堆栈s1中即可,若要poll(remove)一个元素时,则需要借助堆栈s2,将s1中元素pop并且push到s2中,此时s2栈顶元素即是对头元素。之后再将s2中元素pop并且push回s1中。

2.MyQueue2针对MyQueue的优化。堆栈s2中的元素不再回到s1.堆栈s1用于存放最新的push的元素,堆栈s2用于将堆栈s1中的现有元素反序,这样最先入队的几个元素都会在s2中。当MyQueue队列要弹出一个元素时,只需要从s2中弹出元素即可,若s2为空,则将s1中的最新的元素再次pop->push到s2。如此往复。

import java.util.Stack;

class MyQueue{
	private Stack<Integer> s1 = new Stack<Integer>();
	private Stack<Integer> s2 = new Stack<Integer>();
	//time complexity:O(1), space complexity:O(1)
	public boolean offer(int val){
		s1.push(val);
		return true;
	}
	//time complexity:O(n) space complexity:O(n)
	public int poll(){
		if(empty())
			return Integer.MIN_VALUE;
		else{
			while(!s1.empty())
				s2.push(s1.pop());
			int val = s2.pop().intValue();
			while(!s2.empty())
				s1.push(s2.pop());
			return val;
		}
	}
	public boolean empty(){		
		return s1.empty();
	}
}

//improvement for MyQueue
class MyQueue2{
	Stack<Integer> s1 = new Stack<Integer>();
	Stack<Integer> s2 = new Stack<Integer>();
	public boolean offer(int val){
		s1.push(val);
		return true;
	}
	//time complexity gradually reduced, most cases is O(1)
	public int poll(){
		if(s2.empty())
			while(!s1.empty())
				s2.push(s1.pop());
		if(s2.empty())
			return Integer.MIN_VALUE;
		else
			return s2.pop().intValue();	
	}
	public boolean empty(){
		if(s1.empty() && s2.empty())
			return true;
		else
			return false;
	
	}
}

public class Solution{
	public static void main(String[] args){
		//test for MyQueue
		MyQueue mq = new MyQueue();
		int i=0;
		for(;i < 20;i++)
			mq.offer(i);
		
		while(--i > 10 && !mq.empty())
			System.out.print(mq.poll()+" ");
		System.out.println();
		
		for(i=40;i < 50;i++)
			mq.offer(i);
			
		while(!mq.empty())
			System.out.print(mq.poll()+" ");
		System.out.println();	
		
		//test for MyQueue2
		MyQueue2 mq2 = new MyQueue2();
		for(i=100;i < 102;i++)
			mq2.offer(i);
			
		while(i-- != 101 &&!mq2.empty())
			System.out.print(mq2.poll()+" ");
		for(i=102;i < 120;i++)
			mq2.offer(i);
		
		while(!mq2.empty())	
			System.out.print(mq2.poll()+" ");
		System.out.println();
			
	}
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值