1 实现原理介绍
队列和栈的功能在用两个栈实现队列,java代码实现这边文章中已经介绍过了,这里就不多说了,直接讲实现原理:
当需要插入元素时,总是将新元素插入到那个空的队列中,然后再将另一个有数据的队列中的数据,取出插入到存放新元素的队列中,即可完成栈的功能。**注意,每次执行完一次操作,两个队列中,只有一个队列有数据,要么是A,要么是B。**下面画图介绍具体过程:
- 插入
元素1
此时有数据的是队列A
。
- 插入
元素2
此时有数据的是队列B
。
- 插入
元素3
此时有数据的队列A
。
- 删除栈顶元素,
pop
操作
2 java
代码实现
import java.util.LinkedList;
import java.util.Queue;
public class QueueToStack {
public static void main(String[] args) {
QueueToStack queueToStack = new QueueToStack();
queueToStack.push(1);
queueToStack.push(2);
queueToStack.push(3);
queueToStack.push(4);
queueToStack.pop();
int data = queueToStack.top();
System.out.println(data);
System.out.println(queueToStack.empty());
}
Queue<Integer> queueA = new LinkedList<>();
Queue<Integer> queueB = new LinkedList<>();
/**
* Push element x onto stack.
*/
public void push(int x) {
if (queueA.isEmpty() && !queueB.isEmpty()) {
queueA.add(x);
while (!queueB.isEmpty()){
int data = queueB.remove();
queueA.add(data);
}
} else if (!queueA.isEmpty() && queueB.isEmpty()) {
queueB.add(x);
while (!queueA.isEmpty()){
int data = queueA.remove();
queueB.add(data);
}
} else if (queueA.isEmpty() && queueB.isEmpty()) {
queueA.add(x);
}
}
/**
* Removes the element on top of the stack and returns that element.
*/
public int pop() {
if (queueA.isEmpty() && !queueB.isEmpty())
return queueB.remove();
return queueA.remove();
}
/**
* Get the top element.
*/
public int top() {
if (queueA.isEmpty() && !queueB.isEmpty())
return queueB.peek();
return queueA.peek();
}
/**
* Returns whether the stack is empty.
*/
public boolean empty() {
if (queueA.isEmpty() && queueB.isEmpty())
return true;
return false;
}
}
运行结果:
写在最后
欢迎大家关注鄙人的公众号【麦田里的守望者zhg】,让我们一起成长,谢谢。