问题描述:(约瑟夫环) 样例输入: 代码如下:使用链表模拟法
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));
}
}
运行结果如下:
|