由两个栈实现一个队列

要求:实现队列的add,poll,peek操作

package chapter01_stack_and_queue;

import java.util.Stack;
/**
 * 使用两个栈,一个stackPush一个stackPop,
 * push没有条件
 * pop的条件是stackPop为空
 * @author buder_cp
 *
 */
public class TwoStacksImplementQueue {
	public static class TwoStackQueue {
		Stack stackPush = new Stack<>();
		Stack stackPop = new Stack<>();

		public void add(int pushInt) {
			stackPush.add(pushInt);
		}

		public int poll() {
			if (stackPop.empty()) {
				while (!stackPush.isEmpty()) {
					stackPop.push(stackPush.pop());
				}
			}
			return stackPop.pop();
		}

		public int peek() {
			if (stackPop.empty()) {
				while (!stackPush.isEmpty()) {
					stackPop.push(stackPush.pop());
				}
			}
			return stackPop.peek();
		}
	}

	public static void main(String[] args) {
		TwoStackQueue queue = new TwoStackQueue();
		queue.add(12);
		queue.add(32);
		queue.add(34);
		System.out.println(queue.peek());
		System.out.println(queue.poll());
		System.out.println(queue.peek());
	}
}


你可能感兴趣的:(面试相关算法--栈和队列)