用队列来模拟栈.....可以在每次push的时候都将队列的前面所有元素重新插入一遍,这样始终保持这个队列的顺序按照栈的顺序排列即可
class MyStack {
// Push element x onto stack.
Queue<Integer> queue=new LinkedList<Integer>();
public void push(int x) {
queue.add(x);
for( int i=0;i<queue.size()-1;i++ )
{
queue.add( queue.poll() );
//queue.remove();
}
}
// Removes the element on top of the stack.
public void pop() {
queue.remove();
}
// Get the top element.
public int top() {
return queue.peek();
}
// Return whether the stack is empty.
public boolean empty() {
return queue.isEmpty();
}
}
队列模拟栈
本文介绍了一种使用队列模拟栈操作的方法。通过在每次插入元素时调整队列顺序,确保其符合栈的后进先出特性。实现了push、pop、top及empty等核心功能。
3664

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



