单向环形链表(约瑟夫问题)
1、应用场景
1)设编号为1、2、……、n的n个人围坐一圈,约定编号为k的人从1开始报数,数到m的那个人出列,它的下一位又从1开始报数,数到m的人又出列,依次,直到所有人出列。
2、实现
class Node{
public int no;
public Node next;
public Node(int no){
this.no = no;
}
}
// 不带头节点的单向环形链表
class SingleCircleLinkedList{
Node first = null;
// 创建环形链表
public void add(int nums){
if(nums < 1){
System.out.println("链表节点数量小于1");
return;
}
Node cur = null;
for(int i = 1, i <= nums; i++){
Node node = new Node(i);
if(i == 1){
first = node;
first.next = node;
cur = first;
}else{
cur.next = node;
node.next = first;
cur = node;
}
}
}
// 遍历环形链表
public void show(){
if(first == null){
System.out.println("链表为空");
return;
}
Node cur = first;
while(true){
System.out.printf("节点的编号 %d \n", cur.no)
if(cur.next == first){
break;
}
cur = cur.next;
}
}
public void Josephu(int startNo, int countNum, int nums){
if(first == null || startNo < 1 || startNo > nums){
System.out.println("参数不合法");
return;
}
Node cur = first;
while(cur.next != first){
cur = cur.next;
}
for(int i = 0; i < startNo - 1; i++){
cur = cur.next;
first = first.next;
}
while(cur != first){
for(int i = 0; i < countNum - 1; i++){
cur = cur.next;
first = first.next;
}
System.out.printf("节点 %d出环\n", first.no);
first = first.next;
cur.next = first;
}
System.out.printf("最后一个节点是 %d\n", first.no);
}
}