19. Remove Nth Node From End of List
Given the head of a linked list, remove the nth node from the end of the list and return its head.
Follow up: Could you do this in one pass?
- new solution update 2022.02.13
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
|
class Solution { public: ListNode* removeNthFromEnd(ListNode* head, int n) { ListNode* tail = head; for(int i = 0; i < n; i++) { tail = tail->next; } ListNode* dummy = new ListNode(-1,head); ListNode* prev = dummy; while(tail) { prev = prev->next; tail = tail->next; } prev -> next = prev->next->next; return dummy->next; } };
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
|
class Solution { public: ListNode* removeNthFromEnd(ListNode* head, int n) { ListNode* tail = head; ListNode* target = head; while(n--) { tail = tail->next; } if(tail == nullptr) { return head -> next; } while(tail->next != nullptr) { target = target->next; tail = tail->next; } target->next = target->next->next; return head; } };
|