环链表实现
public class JosepfuDome {
public static void main(String[] args) {
CircleSingleQueue circleSingleQueue = new CircleSingleQueue();
circleSingleQueue.addBoy(10);
circleSingleQueue.show();
circleSingleQueue.conutBoy(1,3,10);
}
}
class CircleSingleQueue {
private BoyNode first = null;
public void addBoy(int nums) {
if (nums <= 0) {
System.out.println("请正确的输入");
return;
}
BoyNode cur = null;
for (int i = 1; i <= nums; i++) {
BoyNode boy = new BoyNode(i);
if (i == 1) {
first = boy;
first.setNext(first);
cur = first;
} else {
cur.setNext(boy);
boy.setNext(first);
cur = boy;
}
}
}
public void conutBoy(int startNo, int countNum, int boyNum) {
if (first == null || startNo < 1 || startNo > boyNum) {
System.out.println("参数不正确 请重新输入");
return;
}
for (int i = 0; i < startNo - 1; i++) {
first = first.getNext();
}
BoyNode assistCur = first;
while (true) {
if (assistCur.getNext() == first) {
break;
}
assistCur = assistCur.getNext();
}
while (true) {
if (assistCur == first) {
break;
}
for (int i = 0; i < countNum - 1; i++) {
first = first.getNext();
assistCur = assistCur.getNext();
}
System.out.printf("小耗子%d出圈\n", first.getNo());
first=first.getNext();
assistCur.setNext(first);
}
System.out.printf("%d获胜者\n", first.getNo());
}
public void show() {
if (first == null) {
System.out.println("链表为空");
return;
}
BoyNode cur = first;
while (true) {
System.out.printf("小孩的编号" + cur.getNo() + "\n");
if (cur.getNext() == first) {
break;
}
cur = cur.getNext();
}
}
}
class BoyNode {
private int no;
private BoyNode next;
public BoyNode(int no) {
this.no = no;
}
public int getNo() {
return no;
}
public void setNo(int no) {
this.no = no;
}
public BoyNode getNext() {
return next;
}
public void setNext(BoyNode next) {
this.next = next;
}
}