Remove Nth Node From End of List
Given linked list: 1->2->3->4->5, and n = 2.
After removing the second node from the end, the linked list becomes 1->2->3->5.
Note:
Given _n _will always be valid.
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
if (head == nullptr) return head;
ListNode dummy(-1);
dummy.next = head;
ListNode *fast = &dummy;
ListNode *slow = &dummy;
for (int i = 0; i < n && fast->next != nullptr; i++) {
fast = fast->next;
}
while (fast->next != nullptr) {
fast = fast->next;
slow = slow->next;
}
ListNode *tmp = slow->next;
slow->next = slow->next->next;
delete tmp;
return dummy.next;
}
};
bug version
Case1:
input [1] n = 1
bug at
while (fast->next != nullptr)
Line 19: member access within null pointer of type 'struct ListNode'
slow->next = slow->next->next; // access nullptr
Case2:
input [1 2] n = 2
when delete head node, the bug will occur
need use Dummy Node to delete head
class Solution {
public:
ListNode* removeNthFromEnd(ListNode* head, int n) {
if (head == nullptr) return head;
ListNode *fast = head;
ListNode *slow = head;
for (int i = 0; i < n && fast != nullptr; i++) {
fast = fast->next;
}
while (fast->next != nullptr) {
fast = fast->next;
slow = slow->next;
}
ListNode *tmp = slow->next;
slow->next = slow->next->next;
delete tmp;
return head;
}
};