19. Remove Nth Node From End of List
# Medium
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
ListNode* node = head;
int l = 0;
while(node) {
node = node->next;
l ++;
}
// edge case
if(l == n) {
head = head->next;
return head;
}
node = head;
for(int i = 0; i < l-n-1; i ++) {
node = node->next;
}
node->next = node->next->next;
return head;
}
};
In method 2, must set dump node to avoid the mistake when deleting the head node.
In these two methods, pay attention to the case of deleting the head node.
Last updated
Was this helpful?