单向环形链表应用场景
约瑟夫问题(约瑟夫环)
设编号1,2,...n个人围坐一圈,约定编号为k[1,n]的人从1开始报数,数到m的那个人出列,它的下一位又从1开始报数,数到m的那个人出列,依次类推,直到有人出列为止,由此产生一个出队编号的序列。
假设n有5人,k = 1,从第一个人开始报数,m = 2,数2下。
每次从出队后下一个人开始数
故出队顺序为
2 - 4 - 1 - 5 - 3
代码实现
构建环形链表
- 先创建第一个节点,让first指向该节点,并形成环形
- 后面当我们每创建一个新的节点,就该把节点,加入到已有的环形链表中即可
遍历环形链表
- 先让辅助指针curBoy,指向first
- 然后通过while循环遍历环形链表curBoy.next = first结束
出队
- 创建辅助指针,指向first后一个节点(最后的节点)
- 报数包括自身,故first与helper同时移动m-1次(有本身)
- 将first指向的节点出圈(first前移 first = first.next,helper.next = first)
- 没有指向节点的指针被回收
package cn.imut;
public class Boy {
private int no;
public Boy next; //指向下一个节点,默认为null
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 cn.imut;
public class CircleSingleLinkedList {
//创建first节点(没有编号)
private Boy first = new Boy(-1);
//添加节点,构建环形链表
public void addBoy(int nums) {
//nums做数据校验
if(nums < 1) {
System.out.println("num数据不正确");
return;
}
Boy curBoy = null; //辅助变量
//for循环创建环形链表
for(int i = 1; i <= nums; i++) {
//根据编号创建节点
Boy boy = new Boy(i);
//如果是第一个节点
if(i == 1) {
first = boy;
first.setNext(first); //构成环
curBoy = first; //让curBoy指向第一个节点
}else {
//换线
curBoy.setNext(boy);
boy.setNext(first);
curBoy = boy;
}
}
}
//遍历环形链表
public void showBoy() {
//判断链表是否为空
if(first == null) {
System.out.println("没有节点");
return;
}
//first不动,需要辅助指针
Boy curBoy = first;
while (true) {
System.out.printf("节点编号:%d\n",curBoy.getNo());
if(curBoy.getNext() == first) { //遍历完毕
break;
}
curBoy = curBoy.getNext(); //curBoy后移
}
}
//根据用户的输入,计算出出圈的顺序
/**
*
* @param startNo 从第几个节点开始数数
* @param countNum 数几下
* @param nums 表示最初有多少节点在圈
*/
public void countBoy(int startNo, int countNum, int nums) {
//校验数据
if(first == null || startNo < 1 || startNo > nums) {
System.out.println("参数输入有误!请重新输入");
return;
}
//创建要给辅助指针,帮助节点出圈
Boy helper = first;
while (true) {
if(helper.getNext() == first) { //说明helper指向最后节点
break;
}
helper = helper.getNext();
//报数前,让first与helper移动k-1次
for(int j = 0; j < startNo - 1; j++) {
first = first.getNext();
helper = helper.getNext();
}
//报数时,让first与helper指针同时移动m - 1次,然后出圈
while (true) {
if(helper == first) { //说明圈中只有一个节点
break;
}
//让first和helper指针同时移动countNum - 1
for(int j = 0; j < countNum - 1; j++) {
first = first.getNext();
helper = helper.getNext();
}
//这时first指向的节点,就是出圈的节点
System.out.printf("%d出圈\n", first.getNo());
//这时,将first指向的节点出圈
first = first.getNext();
helper.setNext(first);
}
System.out.printf("最后留在圈中的节点编号%d\n", helper.getNo());
}
}
}
测试
package cn.imut;
public class CircleSingleLinkedListTest {
public static void main(String[] args) {
CircleSingleLinkedList circleSingleLinkedList = new CircleSingleLinkedList();
circleSingleLinkedList.addBoy(5); //加入5个节点
circleSingleLinkedList.showBoy(); //遍历
circleSingleLinkedList.countBoy(1,2,5);
}
}