题目:小明同学把1到n这n个数字按照一定的顺序放入了一个队列Q中。现在他对队列Q执行了如下程序:
while(!Q.empty()){
int x=Q.front(); //取出当前队头的值x
Q.pop(); //弹出当前队头
Q.push(x); //取出这时候队头的值
print("%d\n",x); //输出x
Q.pop(); //弹出这时候的队头
}
做取出队头的值操作的时候,并不弹出当前队头。
小明同学发现,这段程序恰好顺序输出了1,2,3,...,n。现在小明想让你构造出原始的队列,你能做到吗?
输入为n,输出为所求队列
例如
输入2
输出1 2
输入3
输出2 1 3
输入5
输出3 1 5 2 4
分析:以输入n=5为例
输出 值 剩余队列值
(0) null 3 1 5 2 4
(1) 1 5 2 4 3
(2) 1 2 4 3 5
(3) 1 2 3 5 4
(4) 1 2 3 4 5
(5) 1 2 3 4 5 null
可以根据剩余队列值,反向查看插入队列的值
1,当剩余队列中的数字个数小于3时,接下来的直接插入队列;
2,当剩余队列中的数字个数 i 大于等于3时,我们依次取出剩余队列的值并放入辅助队列,直到剩余队列中的数字个数等于1为止。此时将接下的数i-1插入剩余队列,之后再将辅助队列中的值依次插入剩余队列。
接下来是代码
import java.util.LinkedList;
import java.util.Queue;
import java.util.Stack;
public class Main1 {
static final int N=10;
public static void main(String[] args) {
// TODO Auto-generated method stub
int iArrbefore[]=new int[N];
for(int i=1;i<=N;i++){
iArrbefore[i-1]=i;
}
Queue<Integer> queue1=construct(iArrbefore,iArrbefore.length);
Queue<Integer>queue=new LinkedList<Integer>();
while(!queue1.isEmpty()){
queue.offer(queue1.peek());
System.out.print(queue1.poll()+" ");
}
System.out.println();
while(!queue.isEmpty()){
int x=queue.peek();
queue.poll();
queue.offer(x);
x=queue.peek();
System.out.print(x+" ");
queue.poll();
}
}
//构造所求顺序数组
public static Queue<Integer> construct(int[] iArr,int len){
Stack<Integer>stack=new Stack<>();
Queue<Integer>queue1=new LinkedList<>(); //构建剩余队列
for(int a:iArr){
stack.push(a);
}
while(!stack.isEmpty()){
if(queue1.size()<2){//判断剩余队列的个数是否大于2
queue1.offer(stack.pop());
}else{
Queue<Integer>queueTem=new LinkedList<>();//构造辅助队列
while(queue1.size()>1){ //取出剩余队列queue1的值放入辅助数组queueTem,直到queue1.size()=1为止
queueTem.offer(queue1.poll());
}
queue1.offer(stack.peek());
stack.pop();
while(!queueTem.isEmpty()){ //将辅助队列的值依次放入剩余队列
queue1.offer(queueTem.poll());
}
}
}
return queue1;
}
}
结果输出为 8 1 6 2 10 3 7 4 9 5
1 2 3 4 5 6 7 8 9 10