19. 删除链表的倒数第 N 个结点
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode *p1 = head, *p2 = head;
for(int i = 0; i < n; ++i){
p1 = p1->next;
}
if(p1 == nullptr){
return head->next ? head->next: nullptr;
}
while(p1->next != nullptr){
p1 = p1->next;
p2 = p2->next;
}
p2->next = p2->next->next;
return head;
}
};
class Solution:
def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
l1, l2 = head, head
for i in range(n):
l1 = l1.next
if not l1:
return head.next if head.next else None
while l1.next:
l1 = l1.next
l2 = l2.next
l2.next = l2.next.next
return head