一般我們用兩個棧實現隊列
知識點:棧、隊列
將入隊都在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
}
}