Leetcode : 用队列实现栈
要害:元素入队后,把元素x前的其余元素从新出队,再入队,这样x就在队头了,其余元素采纳同样办法入队。
class MyStack { Queue<Integer> queue; /** Initialize your data structure here. */ public MyStack() { queue = new LinkedList<Integer>(); } /** Push element x onto stack. */ public void push(int x) { //获取入队前的元素个数 int length = queue.size(); queue.offer(x); //将x前的元素从新入队再出队,最终x排在队头 for (int i = 0;i < length;i++){ queue.offer(queue.poll()); } } /** Removes the element on top of the stack and returns that element. */ public int pop() { if(empty()){ return -1; }else{ return queue.poll(); } } /** Get the top element. */ public int top() { if(empty()){ return -1; }else{ return queue.peek(); } } /** Returns whether the stack is empty. */ public boolean empty() { if(queue.isEmpty()){ return true; }else{ return false; } }}