Topic:
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.
Given a single linked list, remove the last nth node and return the head of the linked list
idea: maintain two pointers slow,fast,fast first move n step, then slow, fast move at the same time, until fast is empty, delete the node after slow can
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 *prehead =NewListNode (0); -ListNode *fast = prehead, *slow =Prehead; -Slow->next =head; the for(inti =0; I <= N; ++i) -Fast = Fast->Next; - while(FAST) - { +Fast = Fast->Next; -slow = slow->Next; + } ASlow->next = slow->next->Next; at returnPrehead->Next; - } -};
[LeetCode19] Remove Nth Node from End of List