两个栈模拟一个队列和两个队列模拟一个栈

此为网易的一道笔试题。到时候秀逗,不知所云。后来研究之后记录下,以备以后经常翻阅。

栈:先进后出 push和pop

队列:先进先出 offer和poll

(1)两个栈模拟一个队列

即将先进后出实现先进先出。比较容易理解,只要所有数据先往一个栈里push,然后将该栈中的数据依次pop出来再push进第二个队列,则顺序自然颠倒过来了,则每次pop是从第二个队列中取数据。

import java.util.*;
public class StackQueue{
	private Stack<Integer> stack1;
	private Stack<Integer> stack2;
	public StackQueue(){
		stack1 = new Stack<Integer>();
		stack2 = new Stack<Integer>();
	}
	/**
	* push the value
	*/
	public Integer offer(int value){
		stack1.push(value);
		return value;
	}
	/**
	*get the value
	*/
	public Integer poll(){
		Integer result = null;
		if(!stack2.empty()){
			result = stack2.pop();
		}else{
			while(!stack1.empty()){
				int temp = stack1.pop();
				stack2.push(temp);
			}
			if(!stack2.empty()){
				result = stack2.pop();
			}
		}
		return result;
	}

	public static void main(String[] args){
		StackQueue queue = new StackQueue();
		queue.offer(5);
		queue.offer(6);
		queue.offer(4);
		queue.offer(7);
		ArrayList<Integer> list = new ArrayList<Integer>();
		list.add(queue.poll());
		list.add(queue.poll());
		list.add(queue.poll());
		list.add(queue.poll());
		System.out.println("the result is "+list);
	}
}

(2)两个队列模拟一个栈。

栈是先进后出的,队列是先进先出的。即使向(1)中的思路两个队列互换一下,出队的顺序还是不会改变。那么这里就会有一个取巧的地方:每一次入栈,都有一个队列作为备用,另外一个队列用来入队;当出栈的时候,有数据的队列将除队顶之外的元素都出队并入队到备用的队列中,然后队顶元素为出栈的元素。

class QueueStack{
	private Queue<Integer> queue1;
	private Queue<Integer> queue2;

	public QueueStack(){
		queue1 = new LinkedList<Integer>();
		queue2 = new LinkedList<Integer>();
	}
	/**
	* push the value
	*/
	public Integer push(int value){
		if(queue1.isEmpty()){
			queue2.offer(value);
		}else if(queue2.isEmpty()){
			queue1.offer(value);
		}
		return value;
	}

	public Integer pop(){
		Integer result = null;
		if(!queue1.isEmpty()){
			while(queue1.size()>1){
				queue2.offer(queue1.poll());
			}
			result = queue1.poll();
		}else if(!queue2.isEmpty()){
			while(queue2.size()>1){
				queue1.offer(queue2.poll());
			}
			result = queue2.poll();
		}
		return result;
	}

	public boolean empty(){
		if(queue1.isEmpty() && queue2.isEmpty()){
			return true;
		}
		return false;
	}
        public static void main(String[] args){

		QueueStack stack = new QueueStack();
		stack.push(5);
		stack.push(6);
		stack.push(7);
		stack.push(8);
		while(!stack.empty()){
			System.out.print(stack.pop()+",");
		}
	}
}


~~

共勉!

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值