出隊:如果stack2不爲空,每次都彈出棧頂元素;如果stack2爲空,就將stack1中所有元素倒入stack2中,然後彈出stack2中的棧頂元素。若兩個棧都爲空,則無法出隊
package p_13_stack2queue;
import java.util.Stack;
public class Stack2Queue {
private Stack stack1, stack2;
private int maxLength = 0;
public Stack2Queue(int capacity) {
this.maxLength = capacity;
stack1 = new Stack();
stack2 = new Stack();
}
public boolean push(int item) {
//if(stack1.isEmpty() || stack1.size()>maxLength) {
if(stack1.size()>maxLength) {
return false;
}
stack1.push(item);
return true;
}
public int pop(){
// if(stack1.isEmpty() && stack2.isEmpty()){
// return -1;
// }
if(stack2.isEmpty()) {
if(stack1.isEmpty()) {
return -1;
}else {
while(!stack1.isEmpty()){
stack2.push(stack1.pop());
}
return (int) stack2.pop();
}
}
/*if(!stack2.isEmpty()){
return (int)stack2.pop();
}else{
while(!stack1.isEmpty()){
stack2.push(stack1.pop());
}
return (int)stack2.pop();
}*/
//stack2.pop();
return (int)stack2.pop();
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Stack2Queue queue = new Stack2Queue(5);
queue.push(1);
queue.push(2);
System.out.println(queue.pop());
queue.push(3);
System.out.println(queue.pop());
System.out.println(queue.pop());
}
}
第二個我們來看看怎麼使兩個隊列實現棧:出入棧都在queue1完成,而將queue2作爲一箇中轉。
入棧:直接壓入queue1中
出棧:將queue1除最後一個元素外的 所有元素倒入queue1中,再將queue1中的元素出隊,再把queue2中的元素到會queue1中。
優化方案:
入棧:那個隊列不爲空,將八院所入隊到哪個隊列,如果都爲空,就隨機選擇一個。
出棧:把不爲空的隊列中除最後一個元素外的所有元素移動到另一個隊列中,然後出隊最後一個元素。
代碼實現:
package p_13_stack2queue;
import java.util.LinkedList;
public class Queue2Stack {
private LinkedList queue1, queue2;
int maxLen = 0;
public Queue2Stack(int capacity){
maxLen = capacity;
queue1 = new LinkedList();
queue2 = new LinkedList();
}
public boolean push(int item){
if(size() >= maxLen){
return false;
}
if(queue1.isEmpty()){
queue2.add(item);
}else {
queue1.add(item);
}
return true;
}
public int pop(){
if(size() == 0){
throw new IndexOutOfBoundsException("the stack have null");
}else {
if(queue2.isEmpty()){
while(queue1.size() > 1){
queue2.add(queue1.poll());
}
return (int)queue1.poll();
}else{
while(queue2.size() > 1){
queue1.add(queue2.poll());
}
return (int)queue2.poll();
}
}
}
public int size(){
return queue1.size()+queue2.size();
}
}