一副从1到n的牌,每次从牌堆顶取一张方桌子上,再取一张放到堆底,直到没牌,最后桌子上的牌是从1到n有序,设计程序,输入n,输出牌堆的顺序。
import java.util.LinkedList;
public class T {
public static void main(String[] args) {
test(1);
test(2);
test(3);
test(4);
}
private static void test(int n) {
LinkedList list = new LinkedList();
if (n < 2) {
list.add(n);
System.out.println(list.toString());
return;
}
list.add(n);
for (int i = n - 1; i > 0; i--) {
swapFirstAndLast(list, i);
}
System.out.println(list.toString());
}
private static void swapFirstAndLast(LinkedList<Integer> list, int next) {
int first = list.removeFirst();
list.addLast(first);
list.addLast(next);
}
}