利用两个栈组成一个队列


编写一个类,用两个栈组成一个队列,支持队列的基本操作(add、poll、peek)

import java.util.Stack;

public class Main {
	public static void main(String[] args) {
		TwoStackQueue queue = new TwoStackQueue();
		queue.add(1);
		queue.add(2);
		queue.add(3);
		queue.add(4);
		System.out.println(queue.poll());
		queue.add(5);
		System.out.println(queue.poll());
	}
}

class TwoStackQueue{
	private Stack stackPush;
	private Stack stackPop;
	public TwoStackQueue() {
		this.stackPush = new Stack<>();
		this.stackPop  = new Stack<>();
	}
	
	public void add(int pushInt){
		stackPush.push(pushInt);
	}
	
	public int poll(){
		if (stackPop.empty() && stackPush.empty()) {
			throw new RuntimeException("队列为空");
		}else if (stackPop.empty()) {			
			while (!stackPush.empty()) {
				stackPop.push(stackPush.pop());				
			}
		}
		//当stackPop和stackPush都不为空,直接在stackPop进行弹栈操作即可
		//把stackPop中的元素全部弹栈之后,再将stackPush的元素压入stackPop中。
		return stackPop.pop();
	}
	
	public int peek(){
		if (stackPush.empty() && stackPop.empty()) {
			throw new RuntimeException("队列为空");
		}else if (stackPop.empty()) {
			while (! stackPush.empty()) {
				stackPop.push(stackPush.pop());				
			}
		}
		
		return stackPop.peek();
	}
	
}

转自------程序员代码面试指南IT名企算法与数据结构题目最优解



你可能感兴趣的:(栈,队列)