
【解题思路】
用两个栈,在删除队首元素时直接弹出;在队尾插入元素时,用另一个栈辅助,先把栈中其他元素移过去,把新元素插在栈底,最后把原来的元素恢复回去。
class CQueue {
Stack<Integer> s1;
Stack<Integer> s2;
public CQueue() {
s1 = new Stack<Integer>();
s2 = new Stack<Integer>();
}
public void appendTail(int value) {
while(!s1.isEmpty())
{
s2.push(s1.pop());
}
s1.push(value);
while(!s2.isEmpty())
{
s1.push(s2.pop());
}
}
public int deleteHead() {
if(s1.isEmpty())
{
return -1;
}
else
{
int ans = s1.peek();
s1.pop();
return ans;
}
}
}
/**
* Your CQueue object will be instantiated and called as such:
* CQueue obj = new CQueue();
* obj.appendTail(value);
* int param_2 = obj.deleteHead();
*/
使用双栈实现队列操作
该博客介绍了一种利用两个栈实现队列操作的方法。在`CQueue`类中,`appendTail`方法用于在队尾插入元素,通过将栈s1中的所有元素转移到栈s2,然后将新元素压入s1,最后恢复s2。`deleteHead`方法则用于删除队首元素,直接从s1弹出即可。这种方法巧妙地利用了栈的特性来模拟队列的行为。
474

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



