/**
* 自己的代码1,递归
* 用全局变量idx保存节点是从后往前的第几个值
* 如果是第n个,就return递归得到的结果(即原链表中的下一个节点),从而舍弃当前节点
* 如果不是第n个,就将自身节点的next设为递归得到的结果,从而更新下一个节点,然后return自身节点
* Runtime: 0 ms, faster than 100.00%
* Memory Usage: 36.7 MB, less than 91.68%
*/
class Solution {
int idx = 0;
public ListNode removeNthFromEnd(ListNode head, int n) {
if (head == null)
return null;
ListNode pre = removeNthFromEnd(head.next, n);
if (++idx == n)
return pre;
head.next = pre;
return head;
}
}
/**
* 自己的代码2,快慢指针
* 用快慢指针找到要舍弃的节点的前一个节点,用slow.next = slow.next.next的方法舍弃节点
* 注意需要用一个sentinel节点,否则当需要被舍弃的节点是头节点时无法操作,最后return sentinel.next
* Runtime: 0 ms, faster than 100.00%
* Memory Usage: 36.9 MB, less than 49.80%
*/
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode sentinel = new ListNode(-1, head);
ListNode fast = sentinel, slow = sentinel;
int idx = 0;
while (fast != null && idx++ != n)
fast = fast.next;
if (fast == null)
return null;
while (fast.next != null) {
fast = fast.next;
slow = slow.next;
}
slow.next = slow.next.next;
return sentinel.next;
}
}