1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152
| package com.algorithm.linkedlist;
public class Josephu { public static void main(String[] args) { CircleSingleLinkedList list = new CircleSingleLinkedList(); list.addBoy(125); list.showBoy(); System.out.println(">>>>>>>>>>>>>>"); list.countBoy(10,20,215);
}
}
class CircleSingleLinkedList { private Boy first = new Boy(-1);
public void addBoy(int nums) { if (nums < 1) { System.out.println("nums 值不正确"); return; } Boy curBoy = null; for (int i = 1; i <= nums; i++) { Boy boy = new Boy(i); if (i == 1) { first = boy; first.setNext(first); curBoy = first; } else { curBoy.setNext(boy); boy.setNext(first); curBoy = boy; } } }
public void showBoy() { if (first == null) { System.out.println("链表为空"); return; } Boy curBoy = first; while (true) { System.out.println("小孩编号:" + curBoy.getNo()); if (curBoy.getNext() == first) { break; } curBoy = curBoy.getNext(); } }
public void countBoy(int startNum, int countNum, int nums) { if (first == null || startNum < 1 || startNum > nums) { System.out.println("输入数据有误"); return; } Boy helper = first; while (true) { if (helper.getNext() == first) { break; } helper = helper.getNext(); } for (int i = 0; i < startNum - 1; i++) { first = first.getNext(); helper = helper.getNext(); } while (true) { if (helper == first) { break; } for (int i = 0; i < countNum - 1; i++) { first = first.getNext(); helper = helper.getNext(); } System.out.println("小孩" + first.getNo() + "出圈");
first = first.getNext(); helper.setNext(first); }
System.out.println("最后留在圈中的小孩:" + first.getNo());
}
}
class Boy { private int no; private Boy next;
Boy(int no) { this.no = no; }
public int getNo() { return no; }
public void setNo(int no) { this.no = no; }
public Boy getNext() { return next; }
public void setNext(Boy next) { this.next = next; } }
|