剑指offer-两个队列实现栈操作,两个栈实现队列的操作

1.两个队列实现栈操作

1.1 算法要求

使用两个队列,实现栈的操作
栈的特点是:先入栈,后出栈的特点

1.2 算法的实现思路

1.假设入栈操作的数为1,2,3.那么出栈的顺序是3,2,1。如何使用两个队列实现呢?
2.声明两个队列queue1和queue2.
3.入栈操作,直接将数据添加到queue1中,队列中的数据为1,2,3
4.出栈操作,先将队列queue1中的数据1,2,先出队列,并将其添加到队列queue2中。仅使队列queue1中保留一个值,也就是3,此时两queue1中的值出队列。也就实现了一个栈的基本操作
5.当queue1中的3出队列之后,需要将queue2中只1,2,再出队列,并将其添加到queue1中。然后循环

1.3 算法的实现

public class StackWithTwoQueues {
	
	private static Queue<Object> queue1 = new LinkedList<Object>(); 
	private static Queue<Object> queue2 = new LinkedList<Object>();
	
	/**
	 * 栈中添加元素
	 */
	public static void push(Object obj){
		queue1.add(obj);
	}
	
	/**
	 * 栈中弹出元素
	 */
	public static Object pop(){
		Object obj = null;
		if(!queue1.isEmpty()){
			// 将queue1中的数据,仅保留一个。其他都顺序出队到queue2中
			while(queue1.size()>1){
				queue2.add(queue1.poll());
			}
			if(queue1.size() == 1){
				obj = queue1.poll();
			}
			
			// 将queue2中的值添加到queue1中
			while(!queue2.isEmpty()){
				queue1.add(queue2.poll());
			}
		}
		return obj;
	}
	
	public static void main(String[] args) {
		push(1);
		push(2);
		push(3);
		
		System.out.println(pop());
		System.out.println(pop());
		System.out.println(pop());
		System.out.println(pop());
	}
}

2 两个栈实现队列

2.1 算法要求

两个栈实现队列
队列的特点:从队尾添加元素,从队头删除数据

2.2 算法的实现思路

1.假设添加往队列中添加元素1,2,3.那么目标就是出队列的顺序是1,2,3
2.定义两个栈stack1和stack2.,入队列的操作是往 `stack1` 中添加1,2,3.
3.出队列的操作,先将stack1中的值出栈,并添加到栈stack2中,此时stack2中顺序添加进的顺序是3,2,1
4.从stack2中出栈,就是正好是队列1,2,3的顺序

2.3 算法的实现

public class TowStackQueue {
	private static Stack<Integer> stack1 = new Stack<Integer>();
	private static Stack<Integer> stack2 = new Stack<Integer>();
	
	/**
	 * 往队尾添加元素
	 * @param value
	 */
	public static void appendTail(int value){
		stack1.push(value);
	}
	
	/**
	 * 从队头移除数据,并返回
	 */
	public static Integer delteHead(){
		while(!stack1.isEmpty()){
			stack2.push(stack1.pop());
		}
		return stack2.pop();
	}
	
	public static void main(String[] args) {
		appendTail(1);
		appendTail(2);
		appendTail(3);
		appendTail(4);
		System.out.println(delteHead());
		System.out.println(delteHead());
		System.out.println(delteHead());
		appendTail(5);
		System.out.println(delteHead());
		System.out.println(delteHead());
	}
}	
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值