1链表介绍
将单链表中终端结点的指针端由空指针改为指向头结点,就使整个单链表形成一个环,这种头尾相接的单链表成为单向环形链表。
2.示意图
3.约瑟夫问题
Josephu 问题为:设编号为1,2,… n的n个人围坐一圈,约定编号为k(1<=k<=n)的人从1开始报数,数到m 的那个人出列,它的下一位又从1开始报数,数到m的那个人又出列,依次类推,直到所有人出列为止,由此产生一个出队编号的序列。
4.代码实现
package linked02;
/**
* @author WuChenGuang
*/
public class Boy {
// 节点编号
private int no;
// 指向下一个节点
private Boy next;
public 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;
}
}
package linked02;
/**
* @author WuChenGuang
*/
public class CircleSingleLinkedList {
private Boy first = new Boy(-1);
/**
* 构建环形链表 5
*/
public void addBoy(int nums) {
if (nums < 1) {
System.out.println("数据不正确");
return;
}
Boy temp = null;
for (int i = 1; i <= nums; i++) {
Boy boy = new Boy(i);
// 判断你是否是第一个小孩
if (i == 1) {
first = boy;
first.setNext(first);
temp = first;
} else {
temp.setNext(boy);
boy.setNext(first);
temp = boy;
}
}
}
/**
* 查看环形链表中的节点
*/
public void showBoy() {
if (first == null) {
System.out.println("链表为空..");
return;
}
Boy boy = first;
while (true) {
System.out.printf("小孩子的编号%d\n", boy.getNo());
if (boy.getNext() == first) {
break;
}
boy = boy.getNext();
}
}
/**
* 当调用该方法输入第几个小孩子开始数数,数几次,环形链表中一共几个小孩
*/
public void countBoy(int startNo, int countNum, int nums) {
if (first == null || startNo < 1 || startNo > nums) {
System.out.println("参数输入有错误...");
return;
}
// 定义辅助指针,指向的是环形单链表中的最后一个节点
Boy helper = first;
while (helper.getNext() != first) {
helper = helper.getNext();
}
// 寻找起始位置,把first定义为起始位置
for (int j = 0; j < startNo - 1; j++) {
first = first.getNext();
helper = helper.getNext();
}
// 当小孩进行报数时,数到m的孩子进行出列,让first和helper移动m-1次即可,找到了出列孩子
while (helper != first) {
for (int j = 0; j < countNum - 1; j++) {
first = first.getNext();
helper = helper.getNext();
}
System.out.printf("小孩子%d 出列\n", first.getNo());
first = first.getNext();
helper.setNext(first);
}
System.out.printf("最后出圈的小孩编号%d\n", first.getNo());
}
}
package linked02;
/**
* @author WuChenGuang
*/
public class CircleSingleLinkedListTest {
public static void main(String[] args) {
CircleSingleLinkedList circleSingleLinkedList = new CircleSingleLinkedList();
circleSingleLinkedList.addBoy(5);
circleSingleLinkedList.showBoy();
circleSingleLinkedList.countBoy(1, 2, 5);
}
}
运行结果: