LeetCode 第19题
核心就是要找到要删除的链表的前一个节点
两种方法
递归,只遍历一次。以返回值来表明当前节点是倒数第几个节点,同时创建一个头结点指向head节点,这样可以覆盖要删除head节点的情况
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode before = new ListNode();
before.next = head;
dfs(before, n);
return before.next;
}
public int dfs(ListNode head, int n) {
int res = 1;
if(head.next != null) {
res = dfs(head.next, n) + 1;
}
if(res == n+1) {
head.next = head.next.next;
}
return res;
}
}
结果
双指针,这个要遍历两次链表。使第一个指针和第二个指针的间隔为n+1,这样第二个指针的next为空的时候,就找到了第n个要删除的节点
class Solution {
public ListNode removeNthFromEnd(ListNode head, int n) {
ListNode before = new ListNode();
before.next = head;
ListNode l1 = before;
ListNode l2 = head;
int count = 1;
while(count < n) {
l2 = l2.next;
count++;
}
while(l2.next != null) {
l2 = l2.next;
l1 = l1.next;
}
l1.next = l1.next.next;
return before.next;
}
}
结果