算法思想:创建一个具有n个节点的环形链表,然后每次在这个链表中删除第m个节点,详细思路可以看看注释
public class Solution {
/**
* 环形链表的节点类
*/
class ListNode {
public int value;
public ListNode next = null;
public ListNode(int value) {
this.value = value;
}
}
public int LastRemaining_Solution(int n, int m) {
if (n <= 0 || m <= 0){
return -1;
}
//创建循环链表
ListNode head = new ListNode(0);
ListNode pre = head;
ListNode current = null;
for (int i = 1; i< n; i++) {
current = new ListNode(i);
pre.next = current;
pre = current;
}
//形成环
pre.next = head;
//只要环中个数大于1,就继续删
while (n > 1) {
pre = current = head;
int index = 0;
//首先需要定位到第m个数字
while (index < m - 1) {
pre = current;
current = current.next;
index++;
}
//找到当前需要删除节点的下一个节点
ListNode follow = current.next;
//改变指向,进行删除操作
pre.next = follow;
//圈中数字个数少1
n--;
//将刚删除节点的下一个元素设置为链表的头元素
head = follow;
}
return head.value;
}