Original title Link: https://oj.leetcode.com/problems/remove-nth-node-from-end-of-list/
The problem is to remove the last nth node, by keeping 2 pointers, one fast and one slow, the quick pointer going first n, then the slow pointer going at the same time, until the fast pointer becomes null. This changes the value of the slow pointer to next. (Note that the slow pointer is actually a pointer to the cursor in order to change the value of the pointer to the current node). Personally feel this problem actually must be very careful to do, otherwise it is easy to write wrong. Belong to the idea of simple, but need careful and strong heart.
/** * Definition for singly-linked list. * struct ListNode {* int val; * ListNode *next; * listnode (int x): Val (x), Next (NULL) {} *}; */class Soluti On {public: listnode *removenthfromend (listnode *head, int n) { listnode* fast = head; listnode** slowpp = NULL; int i = 0; while (FAST) { fast = fast->next; ++i; if (i = = N) { slowpp = &head; } else if (i > N) { SLOWPP = & ((*SLOWPP)->next);} } if (*SLOWPP) { listnode* next = (*SLOWPP)->next; listnode* cur = (*SLOWPP); Delete (cur); *SLOWPP = next; } return head; };
[Leetcode] 19-remove Nth Node from End of List