输入第一行为整数m表示有m组测试数据,接下来m行每行一个整数N,N不超过50。
输出m行,每行表示题目所求,用空格隔开。
1 4
3 2 4 1
import java.util.LinkedList; import java.util.List; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); while(scanner.hasNext()) { int m = scanner.nextInt(); for (int i = 0; i < m; i++) { int n = scanner.nextInt(); //按照输入顺序排序 List<Integer> myList = new LinkedList<Integer>(); for (int j = 1; j <= n; j++) { myList.add(j); } while(!myList.isEmpty()) { if(myList.size() >= 3) { System.out.print(myList.get(2)+" "); reSort(myList); continue; }else { System.out.print(myList.remove(0)+" "); } } //换行输出 System.out.println(); } } } public static void reSort(List<Integer> myList) { //重排List:实现将List的前两个元素插入到最后得到一个新的List if (myList.size() >= 3) { int list1 = myList.remove(0); int list2 = myList.remove(0); //删除原来List中第3个元素 myList.remove(0); myList.add(list1); myList.add(list2); } } }
import java.util.ArrayList; import java.util.List; import java.util.Scanner; public class Main{ public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); while (n-->0){ int a = scanner.nextInt(); List<Integer> list = new ArrayList<>(); for (int i = 0; i < a; i++) list.add(i+1);//将所有人抽象成Integer,用list模拟圈 int bs = 1; Integer cbsr;//当前报数人 Integer nextbsr = list.get(0);//下一个报数人 while (list.size() != 0) { cbsr = nextbsr; nextbsr = list.get((list.indexOf(cbsr) + 1) % list.size());//关键 每次在移除报3的人之前找下一个报数人 if (bs % 3 == 0) { list.remove(cbsr);//当前报数人退出 System.out.print(cbsr+(list.size()==0?"":" "));//并输出 } bs++; } System.out.println(); } } }
package nowcoder05.demo30; import java.util.Scanner; public class Main { static class Node{ int value; Node next; public Node(int value) { this.value = value; } } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int m = scanner.nextInt(); for (int i = 0; i < m; i++) { int n = scanner.nextInt(); Node head = new Node(1); Node p = head; for (int j = 2; j <= n; j++) { Node node = new Node(j); p.next=node; p=node; } p.next=head; p=head; while (p.next!=p){ Node pre = p.next; System.out.print(pre.next.value+" "); pre.next= pre.next.next; p= pre.next; } System.out.println(p.value); } } }