欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

用栈实现队列

程序员文章站 2024-03-18 11:51:58
...

代码简单,不在解释

package lesson01;

import java.util.Stack;

public class Code03_TwoStackQueue {

	Stack<Integer> stackPush;
	Stack<Integer> stackPop;

	public Code03_TwoStackQueue() {
		stackPush = new Stack<Integer>();
		stackPop = new Stack<Integer>();
	}

	public void push(int item) {
		stackPush.push(item);
	}

	public int poll() throws Exception {
		if (stackPush.isEmpty() && stackPop.isEmpty()) {
			throw new Exception("Queue is empty!");
		} else if (stackPop.isEmpty()) {
			while (!stackPush.isEmpty()) {
				stackPop.push(stackPush.pop());
			}
		}
		return stackPop.pop();

	}

	public int peek() throws Exception {
		if (stackPush.isEmpty() && stackPop.isEmpty()) {
			throw new Exception("Queue is empty!");
		} else if (stackPop.isEmpty()) {
			while (!stackPush.isEmpty()) {
				stackPop.push(stackPush.pop());
			}
		}
		return stackPop.peek();

	}

	public static void main(String[] args) throws Exception {
		Code03_TwoStackQueue queue = new Code03_TwoStackQueue();
		for (int i = 0; i < 7; i++) {
			queue.push(i);
		}

		for (int i = 0; i < 7; i++) {
			System.out.print(" " + queue.poll());
		}

	}

}

相关标签: 用栈实现队列