在计算机科学中,队列是一种具有先进先出(FIFO)特性的数据结构。在本篇博客中,我们将介绍如何使用两个栈来实现一个队列。这种方法的核心思想是利用栈的特性,即后进先出(LIFO),来模拟队列的先进先出特性。
首先,我们需要创建一个名为MyQueue
的类,该类包含两个栈:stack1
和stack2
。这两个栈将用于实现队列的功能。接下来,我们需要实现队列的基本操作,包括push
、pop
、peek
和empty
。
首先,我们需要创建一个队列类
public class MyQueue {
Stack<Integer> stack1;
Stack<Integer> stack2;
public MyQueue(){
stack1 = new Stack<Integer>();
stack2 = new Stack<Integer>();
}
}
push操作
要将一个元素添加到队列的末尾,我们可以将其压入stack1
。这样,当需要从队列的开头弹出或查看元素时,我们可以从stack1
中依次移除并添加回stack2
的元素,直到只剩下队首元素。最后,将新元素添加到stack1
的顶部。
public void push(int value) {
stack1.push(value);
}
pop操作
要从队列的开头弹出一个元素,我们需要将stack1
中的元素依次移除并添加到stack2
中,直到只剩下队首元素。然后,从stack2
中移除该元素。最后,交换stack1
和stack2
的角色。
public int pop() {
if(stack2.isEmpty()){
while (!stack1.isEmpty()){
stack2.push(stack1.pop());
}
}
return stack2.pop();
}
peek操作
要查看队列的队首元素,我们可以按照与pop
操作相同的步骤,将stack1
中的元素依次移除并添加到stack2
中,直到只剩下队首元素。然后,返回该元素并将所有元素重新放回stack1
。
public int peek(){
if(stack2.isEmpty()){
while (!stack1.isEmpty()){
stack2.push((stack1.pop()));
}
}
return stack2.peek();
}
empty操作
要检查队列是否为空,我们只需检查两个栈是否都为空。如果都为空,则队列为空;否则,队列不为空。
public boolean empty(){
return stack1.isEmpty() && stack2.isEmpty();
}
完整代码
package learn.queue;
import java.util.Stack;
public class MyQueue {
Stack<Integer> stack1;
Stack<Integer> stack2;
public MyQueue(){
stack1 = new Stack<Integer>();
stack2 = new Stack<Integer>();
}
public void push(int value) {
stack1.push(value);
}
public int pop() {
if(stack2.isEmpty()){
while (!stack1.isEmpty()){
stack2.push(stack1.pop());
}
}
return stack2.pop();
}
public int peek(){
if(stack2.isEmpty()){
while (!stack1.isEmpty()){
stack2.push((stack1.pop()));
}
}
return stack2.peek();
}
public boolean empty(){
return stack1.isEmpty() && stack2.isEmpty();
}
}
测试类
public class Test {
public static void main(String[] args) {
MyQueue myQueue = new MyQueue();
System.out.println(myQueue.empty()); // true
myQueue.push(1);
myQueue.push(2);
myQueue.push(3);
System.out.println(myQueue.pop()); // 1
System.out.println(myQueue.pop()); // 2
System.out.println(myQueue.empty()); // false
System.out.println(myQueue.pop()); // 3
System.out.println(myQueue.empty()); // true
}
}
运行效果