Given A linked list, remove the nth node from the end of the list and return its head.
For example,
n = 2. After removing the second node from the end, the linked list becomes 1->2->3->5.
Note:
Given n would always be valid.
Try to do the in one pass.
General Youth Solution:
Set three pointer a\b\c, pointer A and B interval n-1 nodes, with pointer A to traverse the list until the last element, then pointer b points to the node to be deleted, pointer C to pointer B's pre, easy to delete the operation.
Code:
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) { AListNode *target =head; -ListNode *target_pre =NULL; -ListNode *findthelast =head; the - if(Head = =NULL) - returnhead; - + while(--n>0) -Findthelast = findthelast->Next; + A while(findthelast->next) { atTarget_pre =Target; -target = target->Next; -Findthelast = findthelast->Next; - } - - if(Target_pre = =NULL) { inHead = target->Next; - returnhead; to } + -Target_pre->next = target->Next; the * returnhead; $ }Panax Notoginseng};
The solution of Literary wisdom Youth:
1 classSolution2 {3 Public:4listnode* Removenthfromend (listnode* head,intN)5 {6listnode** T1 = &head, *t2 =head;7 for(inti =1; I < n; ++i)8 {9T2 = t2->Next;Ten } One while(T2->next! =NULL) A { -T1 = & (*T1)next); -T2 = t2->Next; the } -*t1 = (*T1)Next; - returnhead; - } +};
"Leetcode" "Easy" Remove Nth Node from End of List