/** Definition for singly-linked list. * struct ListNode {* int val; * ListNode *next; * ListNode (int x) : Val (x), Next (NULL) {}}; */classSolution { Public: ListNode* Removenthfromend (listnode* head,intN) {if(head==null&&head->next==NULL)returnNULL; ListNode* Newhead= (listnode*)malloc(sizeof(ListNode)); Newhead->next=Head; ListNode* pre=Newhead; ListNode* behind=Newhead; N++; for(intI=0; i<n-1; i++) Pre=pre->Next; while(pre->next) {Pre=pre->Next; Behind=behind->Next; } behind->next=behind->next->Next; returnNewhead->Next; }};
The problem is to delete the last nth node, so find the bottom n+1 node first and then delete it. Since it is possible to delete the first node of a linked list, you need to insert an empty head node at the beginning of the list.
Before you write a question, think of several special cases ahead of time:
1. Null is returned when the head pointer is empty or if the list has only one node
2. The node to be deleted is the head node or the tail node
Remove Nth Node from End of List