单向环形链表和约瑟夫问题
单向环形链表和约瑟夫问题
应用场景
当n=5;m=2,k=1时出队列的顺序:2->4->1->5->3
一个节点也能形成环链
构建思路
构建一个单向的环形链表思路
1.先创建第一个节点,让first指向该节点,并形成环形.
2.后面当我们每创建一个新的节点,就把该节点,加入到已有的环形链表中即可.
public void addNode(int nums){
if (nums < 1){
System.out.println("nums的值不正确");
return;
}
//构建辅助指针,帮助创建环形链表
Node temp = null;
for (int i = 1; i <= nums; i++) {
Node node = new Node(i);
if (i==1){
first = node;
first.setNext(first);
temp = first;
}else {
temp.setNext(node);
node.setNext(first);
temp = node;
}
}
}
遍历环形链表
1.先让一个辅助指针(变量)temp,指向first节点
2.然后通过一个while循环遍 历该环形链表即可temp.next == first结束
//遍历环形链表
public void showNode(){
if (first == null){
System.out.println("链表为空");
return;
}
Node temp = first;
while (true){
System.out.printf("节点的编号%d\n",temp.getNo());
if (temp.getNext() == first){
break;
}
temp = temp.getNext();
}
}
约瑟夫问题代码实现
package Linked;
public class Josephu {
public static void main(String[] args) {
CircleSingleLinkedList circleSingleLinkedList = new CircleSingleLinkedList();
circleSingleLinkedList.addNode(5);
circleSingleLinkedList.showNode();
System.out.println("结果");
circleSingleLinkedList.nextKNode(1,2,5);
}
}
class Node{
private int no;
private Node next;
public Node(int no) {
this.no = no;
}
public int getNo() {
return no;
}
public void setNo(int no) {
this.no = no;
}
public Node getNext() {
return next;
}
public void setNext(Node next) {
this.next = next;
}
}
class CircleSingleLinkedList{
Node first = new Node(-1);
//添加节点,构成环形链表
public void addNode(int nums){
if (nums < 1){
System.out.println("nums的值不正确");
return;
}
//构建辅助指针,帮助创建环形链表
Node temp = null;
for (int i = 1; i <= nums; i++) {
Node node = new Node(i);
if (i==1){
first = node;
first.setNext(first);
temp = first;
}else {
temp.setNext(node);
node.setNext(first);
temp = node;
}
}
}
//遍历环形链表
public void showNode(){
if (first == null){
System.out.println("链表为空");
return;
}
Node temp = first;
while (true){
System.out.printf("节点的编号%d\n",temp.getNo());
if (temp.getNext() == first){
break;
}
temp = temp.getNext();
}
}
//删除相应的节点
//startNo开始的位置,step表示数几下,nums是节点数
public void nextKNode(int startNo,int step ,int nums){
if (first == null || startNo < 1 || startNo > nums){
System.out.println("参数输入有误");
return;
}
Node temp = first;
//temp指向first的前一个节点
while (true){
if (temp.getNext() == first){
break;
}
temp = temp.getNext();
}
//先将temp和first移动到相应的位置
for (int i = 0; i <startNo-1 ; i++) {
first = first.getNext();
temp = temp.getNext();
}
//
while (true){
//只有一个节点
if (temp == first){
System.out.printf("删除%d号节点\n",first.getNo());
break;
}
//让temp和first移动step-1次,然后删除节点,first指向的节点就是要删除的节点
for (int i = 0; i <step-1 ; i++) {
first = first.getNext();
temp = temp.getNext();
}
System.out.printf("删除%d号节点\n",first.getNo());
first = first.getNext();
temp.setNext(first);
}
}
}