队列(JAVA)

使用2个栈模拟队列的功能

import java.util.Stack;

/**
 * 使用2个栈模拟队列
 * 队列:先进先出
 * 栈:先进后出
 * 根据2着特性就可以直到用2个栈可以模拟一个队列
 * 一个栈做插入栈,一个栈做弹出栈,弹出的时候,将插入栈的元素依次出栈,入栈到弹出栈中,这时弹出栈的顺序是:
 * 先进插入栈的在弹出栈栈顶,那么依次将弹出栈的元素出栈,就可以实现先进先出了
 *
 */
public class Main {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		MyQueue queue = new MyQueue();
		int[] data = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
		//入队
		System.out.println("入队顺序");
		for(int i : data){
			queue.add(i);
			System.out.print(i+" ");
		}
		System.out.println("");
		System.out.println("出队顺序");
		while(!queue.isEmpty()){
			System.out.print(queue.remove()+" ");
		}
		/**
		 * 输出结果:
		 * 入队顺序
			0 1 2 3 4 5 6 7 8 9 10 
			出队顺序
			0 1 2 3 4 5 6 7 8 9 10 
		 */

	}

}
class MyQueue{
	Stack<Integer> insert = new Stack<Integer>();
	Stack<Integer> remove = new Stack<Integer>();
	//入队操作
	public void add(Integer i){
		insert.push(i);
	}
	//出对操作
	public Integer remove(){
		//如果弹出栈不是空的,直接弹出
		if(!remove.isEmpty()){
			int top = remove.pop();
			return top;
		}else{
			//弹出栈为空,需要经插入栈依次出栈,然后入栈弹出栈,在从弹出栈弹出栈顶元素
			if(insert.isEmpty()){
				//插入栈也没有元素了,此时操作为非法
				return insert.pop();
			}else{
				while(!insert.isEmpty()){
					remove.push(insert.pop());
				}
				return remove.pop();
			}
			
		}
	}
	//判空操作
	public boolean isEmpty(){
		//插入和弹出栈同时为空才能为空
		return insert.isEmpty() && remove.isEmpty();
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值