[leetcode] 225. 用队列实现栈

LeetCode.225 用队列实现栈

栈pop的时候将当前队列的处最后一个元素之外的所有元素出队到另外一个元素里,然后出队最后一个元素即可

public class MyStack {

	List<Integer> first;
	List<Integer> second;

	/**
	 * Initialize your data structure here.
	 */
	public MyStack() {
		first = new ArrayList<Integer>();
		second = new ArrayList<Integer>();
	}

	/**
	 * Push element x onto stack.
	 */
	public void push(int x) {
		first.add(x);
	}

	/**
	 * Removes the element on top of the stack and returns that element.
	 */
	public int pop() {
		while (!first.isEmpty()) {
			second.add(first.get(0));
			first.remove(0);
		}

		Integer integer = second.get(second.size() - 1);
		second.remove(second.size() - 1);

		return integer;
	}

	/**
	 * Get the top element.
	 */
	public int top() {
		while (!first.isEmpty()) {
			second.add(first.get(0));
			first.remove(0);
		}

		Integer integer = second.get(second.size() - 1);

		return integer;
	}

	/**
	 * Returns whether the stack is empty.
	 */
	public boolean empty() {
		return first.isEmpty() && second.isEmpty();
	}
}
posted @ 2019-01-18 00:16  ACBingo  阅读(...)  评论(...编辑  收藏