Remove Nth Node From End of List
问题:删除距离末尾n个距离的结点
分析:先找出距离末尾n个距离的结点其距离开始的距离多少,然后再删除
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: int front; int dfs(ListNode *head,int n,int step) { if(head==NULL) return 0; int h=dfs(head->next,n,step+1)+1; if(h==n) { front=step;} return h; } ListNode *removeNthFromEnd(ListNode *head, int n) { if(head==NULL) return head; front=0; dfs(head,n,1); ListNode *help = new ListNode(0); help->next=head; int t=1; ListNode *ret=help; while(1) { if(t==front) { ret->next=head->next; delete head; break; } ret=ret->next; head=head->next; t++; } return help->next; } };