栈(Stack)是限定仅在表尾进行插入和删除操作的线性表,后进先出。
队列(Queue)是只允许在一端进行插入操作,而在另一端进行删除操作的线性表,先进先出。
class MyStack { Queue<Integer> queue; /** Initialize your data structure here. */ public MyStack() { queue = new LinkedList<>(); } /** Push element x onto stack. */ public void push(int x) { queue.offer(x); for (int i = 0; i < queue.size() - 1; i++) { queue.offer(queue.poll()); } } /** Removes the element on top of the stack and returns that element. */ public int pop() { return queue.poll(); } /** Get the top element. */ public int top() { return queue.peek(); } /** Returns whether the stack is empty. */ public boolean empty() { return queue.isEmpty(); } }
原文:https://www.cnblogs.com/HuangYJ/p/12837542.html