First, the topic
Given a single linked list, delete the last nth node and return the deleted list.
For example: known: 1->2->3->4->5, n = 2.
After processing: 1->2->3->5.
try to iterate through the completion.
Second, analysis
See this question my first feeling is a double pointer, because to delete the number of the last nth, so the spacing of two pointers is this n, when the right hand pointer reaches the end, then the left pointer is the next pointer to delete the node. In fact, there are several special cases:
1, {1,2},n=1;
2, {1,2},n=2;
3. {},0
Of course, one might say that n can be greater than the number of nodes, but this topic has already limited n is valid.
Extensions: 1, n values are not limited
2, linked list is not limited to single-linked list, to remove the bottom of the node from the head of n
/** * 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) { if (head==null| | Head->next==null) return NULL; ListNode *rnode = head; ListNode *lnode = head; for (int i=1; i<=n; i++) { Rnode = rnode->next; } if (rnode==null) { head = head->next; return head; } while (rnode->next!=null) { Lnode = lnode->next; Rnode = rnode->next; } Lnode->next = lnode->next->next; return head; };
Leetcode:remove Nth Node from End of List