算法入门-队栈互换

import java.util.LinkedList;
import java.util.Queue;
import java.util.Stack;

/**
 * 如何仅用队列结构实现栈结构?
 * 如何仅用栈结构实现队列结构?
 * @author Administrator
 *
 */
public class Code03_QueueAndStackConvert {
	
	// 仅用队列结构实现栈结构
	public static class TwoQueueStack {
		private Queue<Integer> data;
		private Queue<Integer> help;
		
		public TwoQueueStack(){
			this.data = new LinkedList<Integer>();
			this.help = new LinkedList<Integer>();
		}
		
		public void push(Integer num){
			this.data.add(num);
		}
		
		public Integer pop(){
			if(this.data.isEmpty()){
				throw new RuntimeException("The stack is empty");
			}
			while(data.size() > 1){
				help.add(data.poll());
			}
			int res = data.poll();
			swap();
			return res;
		}
		
		public Integer peek(){
			if(this.data.isEmpty()){
				throw new RuntimeException("The stack is empty");
			}
			while(data.size() > 1){
				help.add(data.poll());
			}
			int res = data.poll();
			help.add(res);
			swap();
			return res;
		}
		
		public void swap(){
			Queue<Integer> temp;
			temp = data;
			data = help;
			help = temp;
		}
	}

	// 仅用栈结构实现队列结构
	public static class TwoStackQueue {
		private Stack<Integer> pushStack;
		private Stack<Integer> popStack;
		
		public TwoStackQueue() {
			this.pushStack = new Stack<>();
			this.popStack = new Stack<>();
		}
		
		public void push(Integer num) {
			pushStack.push(num);
		}
		
		public Integer poll() {
			if(this.popStack.isEmpty() && this.pushStack.isEmpty())
				return null;
			pour();
			return popStack.pop();
		}
		
		public Integer peek() {
			if(this.popStack.isEmpty() && this.pushStack.isEmpty())
				return null;
			pour();
			return popStack.peek();
		}
		
		public void pour() {
			if(!this.popStack.isEmpty())
				return ;
			while(!this.pushStack.isEmpty()){
				popStack.push(pushStack.pop());
			}
		}
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值