问题描述:(约瑟夫环) ![在这里插入图片描述](https://img-blog.csdnimg.cn/54fdc96eab6648df82883fcf24e914c6.png) 样例输入: ![在这里插入图片描述](https://img-blog.csdnimg.cn/dd0f96cc13404ea49cfe08c671f7f4a1.png) ![在这里插入图片描述](https://img-blog.csdnimg.cn/6e164ec12d7044c4a6212e8d2bc4ffa3.png) 代码如下:使用链表模拟法
import java.util.Scanner;
public class FindTheWinner {
class Node{
int data;
Node next;
public Node(int data) {
this.data = data;
}
}
public int findTheWinner(int n, int k) {
if (k==1) return n;
Node first=new Node(1);
Node p=first;
for (int i = 2; i <=n ; i++) {
p.next=new Node(i);
p=p.next;
}
p.next=first;
Node p1=first;
Node pre=null;
int cnt=1;
while (p1!=pre){
pre=p1;
p1=p1.next;
cnt++;
if (cnt==k){
pre.next=p1.next;
cnt=1;
p1=pre.next;
}
}
return p1.data;
}
public static void main(String[] args) {
Scanner scanner=new Scanner(System.in);
int n=scanner.nextInt();
int k=scanner.nextInt();
FindTheWinner findTheWinner=new FindTheWinner();
System.out.println(findTheWinner.findTheWinner(n,k));
}
}
运行结果如下: ![在这里插入图片描述](https://img-blog.csdnimg.cn/7a0db5a1b2e2491baa98436bbc83f04d.png)
|