题目:环形链表的约瑟夫问题
思路:
建立一个环形链表,然后循环删除,直到只剩下一个元素。
代码:
import java.util.*;
public class Solution {
/**
*
* @param n int整型
* @param m int整型
* @return int整型
*/
public int ysf (int n, int m) {
// write code here
if (n < 1 || m < 1) {
return 0;
}
Node pre = new Node(1);
Node first = pre;
for (int i = 2; i <= n; i ++) {
Node cur = new Node(i);
pre.next = cur;
pre = pre.next;
if (i == n) {
pre.next = first;
}
}
while (pre.next != pre) {
for (int i = 0; i < ((m - 1) % n); i ++) {
first = first.next;
pre = pre.next;
}
pre.next = first.next;
first.next = null;
first = pre.next;
n -= 1;
}
return pre.val;
}
}
class Node {
int val;
Node next;
public Node (){}
public Node (int v) {
this.val = v;
this.next = null;
}
}