惯性思维以为也要用两个queue 这个题用一个就可以了 queue可以很方便的翻转顺序,把每个队头的poll出来add到后面就好了
注意queue的实现方式 是用linkedlist
class MyStack {
// Push element x onto stack
private Queue<Integer> que = new LinkedList<Integer>();
public void push(int x) {
que.add(x);
for ( int i = 0; i < que.size() - 1; i ++){
que.add( que.poll() );
}
}
// Removes the element on top of the stack.
public void pop() {
que.poll();
}
// Get the top element.
public int top() {
return que.peek();
}
// Return whether the stack is empty.
public boolean empty() {
if ( que.size() == 0 )
return true;
else
return false;
}
}

本文介绍了一种利用单个队列实现栈的基本操作(压栈、弹栈、获取栈顶元素和判断栈是否为空)的方法。通过将元素添加到队列尾部并循环移除队首元素再重新加入队尾,可以方便地实现栈的功能。
401

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



