Java codeimport java.util.LinkedList;
import java.util.Stack;
public class TestIO {
/**
* 穷举每一种可能的出栈序列
* @param inQueue
* @param stack
* @param outQueue
*/
public static void getStackSequence(LinkedList inQueue,Stack stack,LinkedList outQueue){
if(inQueue.isEmpty()&&stack.isEmpty()){
//输出可能的出栈序列
while(!outQueue.isEmpty()){
System.out.print(outQueue.poll()+" ");
}
System.out.println();
}else if(!inQueue.isEmpty()&&!stack.isEmpty()){
//保存现场
LinkedList tempInQueue=new LinkedList(inQueue);
LinkedList tempOutQueue=new LinkedList(outQueue);
Stack tempStack=new Stack();
for(int i=0;i
//队首元素入栈
stack.push(inQueue.poll());
getStackSequence(inQueue, stack, outQueue);
//还原现场
inQueue=tempInQueue;
outQueue=tempOutQueue;
stack=tempStack;
//栈顶元素出栈
outQueue.offer(stack.pop());
getStackSequence(inQueue, stack, outQueue);
}else if(!inQueue.isEmpty()&&stack.isEmpty()){
//队首元素入栈
stack.push(inQueue.poll());
getStackSequence(inQueue, stack, outQueue);
}else if(inQueue.isEmpty()&&!stack.isEmpty()){
//栈顶元素出栈
outQueue.offer(stack.pop());
getStackSequence(inQueue, stack, outQueue);
}else{
}
}
/**
* 封装输出,获得内部算法所需要的接口
* @param in
* @param out
*/
private static void init(String[] in){
Stack stack=new Stack();
LinkedList outQueue=new LinkedList();
LinkedList inQueue=new LinkedList();
for(int i=0;i
getStackSequence(inQueue, stack, outQueue);
}
public static void main(String[] args){
String[] in={"1","2","3","4","5"}; //入栈顺序
init(in);
}
}