This question if according to normal idea, usually is the two sides traverse, the first time is calculates the chain list the length, then determines the reciprocal nth node the positive sequence number, then accesses can.
The better way is to find a pointer p point to the head node after the n+1 nodes, and then at the same time to move the opposite node and p back, if p=null, then the head pointer is exactly pointing to the penultimate n+1 node. Here is a question, if n is exactly equal to the length of the list, it is obvious that the head pointer is pointing at the head node, and there is no precursor to the head node, and that sentence in the code solves the problem, that is, when there is no n+1 judgment, then NULL is the case.
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 *end =head; -ListNode *f =head; - inti =0; the while(End! = null&&i<n+1) - { -End = End->Next; -i++; + if (end = = null&&i<n+1)return head = head->Next ; + } A while(End! =NULL) at { -Head = head->Next; -End = End->Next; - } -Head->next = head->next->Next; - returnF; in } -};
Leetcode Remove Nth Node from End of List