LeetCode第19题:删除链表倒数第N个节点
这道题我这里用了递归来获取链表深度,判定到了指定位置后修改指针即可。
当然链表里涉及到固定数N的,都可以用双指针解决,快指针比慢指针快N步,判定快的到终点时对慢的那个指针处理即可。这种方案各位可以自己试试
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
int totalCount = remove(head, n);
return totalCount == n ? head.next : head;
}
public int remove(ListNode head, int n) {
if (head == null) {
return 0;
}
int count = remove(head.next, n) + 1;
if (n + 1 == count) {
head.next = head.next.next;
}
return count;
}
}