两个栈实现一个队列:
我们都知道栈的特性为先入后出,而队列则是先入先出。如何使用两个栈来实现一个队列呢?
思路:
用栈s1作为存储空间,栈s2作为缓存空间。
入队时,将数据压入s1中。
出队时,将数据从s1中弹出再压入s2中,再从s2弹出一个数据,再次将数据弹出并压入s1中。
出队操作图解:
实现代码:
class SeqStack{
// 存储栈的元素的数组
protected T[] stack;
// top表示栈顶的位置
private int top;
public SeqStack(){
this(10);
}
public SeqStack(int size){
this.stack = (T[])new Object[size];
this.top = 0;
}
public void push(T val){
if(full()){
// 栈如果满了,要进行内存2倍扩容
this.stack = Arrays.copyOf(this.stack,
this.stack.length*2);
}
this.stack[this.top] = val;
this.top++;
}
public void pop(){
if(empty()) {
return;
}
this.top--;
if(this.top < this.stack.length/2){
this.stack = Arrays.copyOf(this.stack, this.stack.length/2);
}
}
public T top(){
return this.stack[this.top - 1];
}
public boolean full(){
return this.top == this.stack.length;
}
public boolean empty(){
return this.top == 0;
}
}
/**
- 用两个栈实现一个队列
- @param
*/
class Queue{
private SeqStack s1;
private SeqStack s2;
public Queue(){
this.s1 = new SeqStack<>();
this.s2 = new SeqStack<>();
}
public Queue(int size){
this.s1 = new SeqStack<>(size);
this.s2 = new SeqStack<>(size);
}
public void offer(E value){
this.s1. push(value);
}
public E poll(){
E data = null;
while(!this.s1.empty()){
data = s1.top();
s1.pop();
if(s1.empty()){
break;
}
this.s2.push(data);
}
while(!this.s2.empty()){
this.s1.push(s2.top());
s2.pop();
}
return data;
}
public E peek(){
E data = null;
while(!this.s1.empty()){
data = s1.top();
s1.pop();
this.s2.push(data);
}
while(!this.s2.empty()){
this.s1.push(s2.top());
s2.pop();
}
return data;
}
public boolean full(){
return (this.s1.full());
}
public boolean empty(){
return (this.s1.empty());
}
运行结果: