import java.util.EmptyStackException;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
import java.util.Stack;
public class H06 {
/**
* @return
* @给定一个正整数N代表火车数量,0<N<10,接下来输入火车入站的序列,
* 一共N辆火车,每辆火车以数字1-9编号。
* 要求以字典序排序输出火车出站的序列号。
*
* 思路:
* 要进站的火车组成队列,排前面的先进
* 车站是个栈,后进,先出
* 出站的火车可以简单的用String存储
* 当进站队列和火车栈都空了的时候火车全部出战,打印出站的序列
* 考虑到字典序,当有车可以出战时,优先出站,然后递归
* 当有车可以进站的时候,进站,然后把结果递归
*
* 本题的递归用tmp保护了现场
*/
public static void main(String[] args)
{
Scanner cin = new Scanner(System.in);
int num=cin.nextInt();
Queue<Integer> qToIn = new LinkedList<Integer>();
for (int i = 0; i<num; i++)
{
qToIn.add(cin.nextInt());
}
cin .close();
Stack<Integer> sToOut = new Stack<Integer>();
String out = "";
stationDispatch(qToIn,sToOut,out);
}
public static void stationDispatch(Queue<Integer> qToIn,
Stack<Integer> sToOut,String out)
{
boolean hasqToIn = true;
boolean hassToOut = true;
if (qToIn.peek() == null)
{
hasqToIn = false;
}
try
{
sToOut.peek();
} catch (EmptyStackException e)
{
hassToOut = false;
}
if (! hasqToIn && ! hassToOut )
{
System.out.println(out);
return;
}
if (hassToOut)
{
Queue<Integer> qToInTmp = new LinkedList<Integer>(qToIn);
Stack<Integer> sToOutTmp = (Stack<Integer>)sToOut.clone();
String outTmp=out;
outTmp += sToOutTmp.pop().toString();
stationDispatch(qToInTmp,sToOutTmp,outTmp);
}
if (hasqToIn)
{
Queue<Integer> qToInTmp = new LinkedList<Integer>(qToIn);
Stack<Integer> sToOutTmp = (Stack<Integer>)sToOut.clone();
String outTmp=out;
sToOutTmp.push(qToInTmp.poll());
stationDispatch(qToInTmp,sToOutTmp,outTmp);
}
}
}