一.单向环形链表构建图:
1.第一张:
2.第二张
3.第三张
至此便成功插入一个节点到一个单向环形链表中
二.使用单向环形链表解决约瑟夫问题
约瑟夫问题:设编号为1,2,3...,n的n个人围成一圈,约定编号为k(1<=k<=n)的人
从1开始报数,数到m的那个人出列,它的下一位从1数到m然后出列,
以此类推直到全部人出列为止,产生一个出队的编号序列
1.创建一个BoyNode类
public class BoyNode {
/**
* 编号
*/
public int id;
/**
* 姓名
*/
public String name;
/**
* 下一个节点
*/
public BoyNode nextNode;
public BoyNode(int id, String name) {
this.id = id;
this.name = name;
}
@Override
public String toString() {
return "BoyNode{" +
"id=" + id +
", name='" + name + '\'' +
'}';
}
}
2.创建一个BoyRingLinked类
public class BoyRingLinked {
/**
* 第一个节点
*/
public BoyNode first;
/**
* 添加nodeSize个节点到环形链表中
*/
public void addNode(int nodeSize){
BoyNode temp = null;
BoyNode current = null;
for (int i=1;i<=nodeSize;i++){
if (first == null){
first = new BoyNode(i,""+i);
first.nextNode = first;
temp = first;
continue;
}
if (temp.nextNode != null){
current = new BoyNode(i,""+i);
temp.nextNode = current;
current.nextNode = first;
temp = current;
}
}
}
/**
* 查询环形链表中的节点
*/
public void queryAllNode(){
BoyNode current = first;
if (current == null){
System.out.println("空环形链表");
return;
} else {
System.out.println(current);
}
while (true){
if (current.nextNode == first){
return;
}{
System.out.println(current.nextNode);
}
current = current.nextNode;
}
}
/**
* 调用此方法解决约瑟夫问题
*/
public void ringLinkedOut(int start,int step,int nodeSize){
addNode(nodeSize);
BoyNode temp = queryBoyEndNode();
for (int i=1;i<start;i++){
temp = temp.nextNode;
}
for (;;){
if (temp.nextNode == temp){
System.out.println(temp);
break;
}
for (int i=1;i<=step;i++){
if (i == step){
System.out.println(temp.nextNode);
temp.nextNode = temp.nextNode.nextNode;
break;
}
temp = temp.nextNode;
}
}
}
/**
* 查询双向链表的尾节点
*/
public BoyNode queryBoyEndNode(){
BoyNode current = first;
while (true){
if (current.nextNode == first){
return current;
}
current = current.nextNode;
}
}
}