逆序打印

来源:互联网 发布:白兔商标查询软件 编辑:程序博客网 时间:2024/06/06 18:58
题目:

小易有一个长度为n的整数序列,a_1,...,a_n。然后考虑在一个空序列b上进行n次以下操作:
1
、将a_i放入b序列的末尾
2
、逆置b序列
小易需要你计算输出操作n次之后的b序列。

思路:你若按照题目要求来回做折腾操作,是可以得到结果,倒是ac肯定超时,那么我们就要寻找规律,并且寻找适合的数据结构,规律就是交替的向前或向后插入数据,然后再看逆不逆序。




public class Problem4 {    public static void main(String[] args){        Scanner in=new Scanner(System.in);        while (in.hasNext()) {            int n=in.nextInt();            Deque<Integer> deque=new LinkedList<Integer>();            boolean convert=false;            for (int i=0;i<n;i++){                if (convert) {                    deque.addLast(in.nextInt());                }else {                    deque.addFirst(in.nextInt());                }                convert=!convert;            }            if (convert) {                while (deque.size() != 1) {                    System.out.print(deque.pollFirst()+" ");                }                System.out.println(deque.pollFirst());            }else {                while (deque.size() != 1) {                    System.out.print(deque.pollLast()+" ");                }                System.out.println(deque.pollLast());            }        }        in.close();    }}