【剑指offer系列】62-圆圈中最后剩下的数字(关键字:约瑟夫循环链表通用解法)

题目:
0,1,n-1 这 n 个数字排成一个圆圈,从数字start 开始,每次从这个圆圈里删除第 step个数字。求出这个圆圈里剩下的最后一个数字。

例如

0、1、2、3、4、5、6、7、8、9、10 这 11 个数字组成一个圆圈,从数字 2开始每次删除第 3 个数字,则删除的数字依次是

输入: 10 2 3
输出:8

删除的第:1个节点为4
删除的第:2个节点为7
删除的第:3个节点为10
删除的第:4个节点为2
删除的第:5个节点为6
删除的第:6个节点为0
删除的第:7个节点为5
删除的第:8个节点为1
删除的第:9个节点为9
删除的第:10个节点为3
最后一个节点为8

public class Main62
{public static int i = 1;private static void yuesefucicle(int n, int start, int step){//1.创建循环链表LinkedNode head = new LinkedNode(0);LinkedNode temp = head;for (int i = 1; i <= n; i++){LinkedNode newNode = new LinkedNode(i);temp.next = newNode;newNode.next = head;temp = temp.next;}//2.根据start移动head和temp指针,移动start次int index = 0;while (index++ < start){head = head.next;temp = temp.next;}//上述初始化工作完成,开始剔while (head != temp){//只剩一个节点//3.移动步长step次两个指针index = 0;while (index++ < step-1){head = head.next;temp = temp.next;}//4.删除节点System.out.println("删除的第:"+i+ "个节点为"+head.val);i++;head = head.next;temp.next = head;}System.out.println("最后一个数为"+head.val);}public static void main(String[] args){Scanner sc = new Scanner(System.in);int n = sc.nextInt();//0->n个人int start = sc.nextInt();//从某个数字开始int step = sc.nextInt();//每隔step个数字踢出去一个yuesefucicle(n,start,step);}
}
class LinkedNode
{public Integer val;public LinkedNode(Integer val){this.val = val;}public LinkedNode next;
}