Leetcode-19. Remove Nth Node From End of List

题目

删除链表的倒数第n个元素

思路

双指针p1, p2,p1先移动到链表的第n个元素,然后p1和p2一起移动,当p2到达末尾时,p1指向的元素即为要删除的元素的前一个元素。注意处理n大于链表长度的情况。

代码

class Solution { public: ListNode* removeNthFromEnd(ListNode* head, int n) { if(head == NULL) return head; ListNode *p1 = head, *p2 = head; while(n--) p1 = p1->next; if(p1 == NULL){ head = head->next; return head; } while(p1->next) { p1 = p1->next; p2 = p2->next; } p2->next = p2->next->next; return head; } };