用两个栈实现队列java
时间: 2024-02-11 13:57:05 浏览: 30
在Java中,可以通过使用两个栈来实现队列。具体实现步骤如下:
1. 创建一个名为CQueue的类,该类包含两个私有属性stack1和stack2,分别表示两个栈。
2. 实现CQueue的构造函数和析构函数。
3. 实现CQueue的appendTail函数,将元素插入到stack1中。
4. 实现CQueue的deleteHead函数,删除队列头部的元素。首先判断stack2的大小,如果为空,则将stack1中的所有元素依次弹出并压入stack2中。然后从stack2中弹出并返回头部元素。
代码示例:
```
import java.util.Stack;
class CQueue<T> {
private Stack<T> stack1;
private Stack<T> stack2;
public CQueue() {
stack1 = new Stack<>();
stack2 = new Stack<>();
}
public void appendTail(T node) {
stack1.push(node);
}
public T deleteHead() throws Exception {
if (stack2.isEmpty()) {
while (!stack1.isEmpty()) {
stack2.push(stack1.pop());
}
}
if (stack2.isEmpty()) {
throw new Exception("Queue is empty.");
}
return stack2.pop();
}
}
```