【 腾讯精选练习 50 题】用队列实现栈

1. 题目描述

2. 题目分析

  •  有一说一,题目有点沙雕
  • 用两个队列来实现一个栈
  • 栈:先进后出、队列:先进先出
  • 我们用两个队列来模拟栈,一个队列当主栈,一个队列用来辅助,我们在push的时候,将主栈的元素转移到辅助栈中,然后push至主栈,再从辅助栈拿回所有的数据,这样,一个模拟的栈基本构成
  • pop(),直接应用队列的poll()
  • top(),直接应用队列的peek()
  • empty(),直接应用队列的isEmpty()

3. 题目代码

public class Stack {
	Queue<Integer> queue1 = new LinkedList<Integer>();
	Queue<Integer> queue2 = new LinkedList<Integer>();

	/**
	 * Initialize your data structure here.
	 * 
	 * @return
	 */
	public Stack() {
	}

	/** Push element x onto stack. */
	public void push(int x) {
		while (!queue1.isEmpty()) {
			queue2.add(queue1.peek());
			queue1.poll();
		}
		queue1.add(x);
		while (!queue2.isEmpty()) {
			queue1.add(queue2.peek());
			queue2.poll();
		}
	}

	public int pop() {
		int temp = queue1.peek();
		queue1.poll();
		return temp;
	}

	/** Get the top element. */
	public int top() {
		return queue1.peek();
	}

	/** Returns whether the stack is empty. */
	public boolean empty() {
		return queue1.isEmpty();
	}
}

猜你喜欢

转载自blog.csdn.net/qq_40915439/article/details/107672047
今日推荐