一般我们用两个栈实现队列
知识点:栈、队列
将入队都在stack1中进行,出队在stack2中进行。
- 入队:直接把元素压入stack1中。
- 出队:如果stack2不为空,则直接弹出stack2中的元素;如果stack2为空,则将stack1中的所有元素倒入stack2中然后弹出stack2中的栈顶元素。同源,若两个栈都为空栈,则队列为空队,无法出队。
代码实现
package edu.xatu1;
public class StackQuene {
private Stack stack1;
private Stack stack2;
private int maxLength;
public StackQuene(int capacity){
maxLength = capacity;
stack1 = new Stack(capacity);
stack2 = new Stack(capacity);
}
public boolean put(int item){
if(stack1.isFull() || maxLength == size()){
//满了
return false;
}
stack1.push(item);
return true;
}
public int poll(){
if(!stack2.isEmpty()){
return stack2.pop();
}else{
while(!stack1.isEmpty()){
stack2.push(stack1.pop());
}
return stack2.pop();
}
}
public int size(){
return stack1.size() + stack2.size();
}
}
测试代码
package edu.xatu1;
public class StackQueneTest {
public static void main(String[] args){
StackQuene quene = new StackQuene(5);
quene.put(1);
quene.put(2);
System.out.println(quene.poll()); //1
quene.put(3);
quene.put(4);
System.out.println(quene.poll()); //2
System.out.println(quene.poll());//3,此次将3、4两个元素从stack1倒入stack2
}
}