问题
队列实现栈
例子
思路
存的时候,先存到队列,然后把该数之前的数顺序取出,插到后面
放的时候,本来是在最后一个,但是把它前面的都放在它后面,就变成了它是第一个
代码
class MyStack {
Queue<Integer> q = new LinkedList<>();
/** Initialize your data structure here. */
public MyStack() {
}
/** Push element x onto stack. */
public void push(int x) {
q.add(x);
for(int i=0; i<q.size()-1; i++) {
q.add(q.poll());
}
}
/** Removes the element on top of the stack and returns that element. */
public int pop() {
int n = q.poll();
return n;
}
/** Get the top element. */
public int top() {
return q.peek();
}
/** Returns whether the stack is empty. */
public boolean empty() {
return q.size()==0;
}
}

2080

被折叠的 条评论
为什么被折叠?



