使用栈实现队列结构、使用队列实现栈结构

使用栈实现队列结构

public static class stackToQueue{
		Stack<Integer> stack;
		Stack<Integer> help;
		
		public stackToQueue(){
			stack = new Stack<Integer>();
			help = new Stack<Integer>();
		}
		
		public void add(int num){
			stack.add(num);
		}
		//因为栈是先进后出,而队列是先进先出,所以只要将栈的值逐个保存到另一个栈,再弹出
		public int remove(){
			if(stack.empty()&&help.empty()){
				throw new ArrayIndexOutOfBoundsException();
			}else if(help.empty()){
				while(!stack.empty()){
					help.add(stack.pop());
				}
			}
			return help.pop();
		}
		
		public int peek(){
			if(stack.empty()&&help.empty()){
				throw new ArrayIndexOutOfBoundsException();
			}else if(help.empty()){
				while(!stack.empty()){
					help.add(stack.pop());
				}
			}
			return help.peek();
		}

	}

 

 

队列实现栈

public static class queueToStack{
		private Queue<Integer> queue;
		private Queue<Integer> help;
		
		
		public queueToStack(){
			queue = new LinkedList<Integer>();
			help = new LinkedList<Integer>();
		}
		
		public void add(int num){
			queue.add(num);
		}
		//因为是队列是先进先出,栈是先进后出,所以栈删除的时候会先删除最后一个进入的元素
		public int remove(){
			if(queue.isEmpty()){
				throw new ArrayIndexOutOfBoundsException();
			}
			while(queue.size()>1){
				help.add(queue.remove());
			}
			
			int res = queue.remove();
			swap();
			return res;
			
		}
		
		public int peek(){
			if(queue.isEmpty()){
				throw new ArrayIndexOutOfBoundsException();
			}
			while(queue.size()>1){
				help.add(queue.remove());
			}
			int res = queue.remove();
			help.add(res);
			swap();
			return res;
		}
		
		
		public void swap(){
			Queue<Integer> temp = queue;
			queue = help;
			help = temp;
		}
	}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值