Topic links
Title Requirements:
Given A linked list, remove the nth node from the end of the list and return its head.
For example,
1,2,3,4,52. 1,2,3,5.
Note:
Given n would always be valid.
Try to do the in one pass.
The conventional idea of this problem is to calculate the length of the linked list Len, and then move the head pointer len-n step to reach the truncated point. The specific procedure is as follows (4MS):
1 /**2 * Definition for singly-linked list.3 * struct ListNode {4 * int val;5 * ListNode *next;6 * ListNode (int x): Val (x), Next (NULL) {}7 * };8 */9 classSolution {Ten Public: Onelistnode* Removenthfromend (listnode* head,intN) { A if(!head) - returnhead; - the intLen =0; -ListNode *start =head; - while(start) - { +len++; -Start = start->Next; + } A at if(len = =N) - { -Start =head; -Head = head->Next; - Deletestart; -Start =nullptr; in returnhead; - } to +ListNode *prenode =head; -Start = prenode->Next; the intK =1; * while(K < Len-N) $ {Panax NotoginsengPrenode =start; -Start = start->Next; thek++; + } A thePrenode->next = start->Next; + Deletestart; -Start =nullptr; $ $ returnhead; - } -};
Another clever way to do this is to define a slow pointer (the initial value is the parent pointer of the head pointer), let the head pointer move N, and then move the head pointer and a slow pointer at the same time until the head pointer is empty, then the next node that the slow pointer points to is the truncated point. The specific program date is as follows (4MS):
1 /**2 * Definition for singly-linked list.3 * struct ListNode {4 * int val;5 * ListNode *next;6 * ListNode (int x): Val (x), Next (NULL) {}7 * };8 */9 classSolution {Ten Public: Onelistnode* Removenthfromend (listnode* head,intN) { A if(!head) - returnhead; - theListNode *dummy =New(nothrow) ListNode (int_min); - assert (dummy); -Dummy->next =head; - + for(inti =0; I < n; i++) -Head = head->Next; + AListNode *prenode =dummy; at while(head) - { -Head = head->Next; -Prenode = prenode->Next; - } - inListNode *delnode = prenode->Next; -Prenode->next = delnode->Next; to DeleteDelnode; +Delnode =nullptr; - theHead = dummy->Next; * Deletedummy; $dummy =nullptr;Panax Notoginseng - returnhead; the } +};
Leetcode "Linked list": Remove Nth Node from End of List