This is a classic problem of linked list. You may solve it using the pointers. The tricky part lies with the head pointer may also being the one that's required to being removed. Handle this carefully.
1 classSolution {2 Public:3ListNode *removenthfromend (ListNode *head,intN) {4ListNode *pre, *cur;5Pre = cur =head;6 inti =0;7 for(; i < n; i++)8cur = curNext;9 if(!cur)returnHeadNext;Ten while(curnext) { OnePre = PreNext; Acur = curNext; - } -Pre--next = pre--NextNext; the returnhead; - } -};
You may create a Dummy That points to Head To facilitate the removal.
1 classSolution {2 Public:3listnode* Removenthfromend (listnode* head,intN) {4listnode* dummy =NewListNode (0);5Dummy-Next =head;6listnode* pre =dummy;7listnode* cur =dummy;8 for(inti =0; I < n; i++)9cur = curNext;Ten while(curnext) { OnePre = PreNext; Acur = curNext; - } -Listnode* del = PreNext; thePre, next = DelNext; - Deletedel; - returnDummyNext; - } +};
This link have a much shorter solution using pointers to pointers, which are a little difficult to understand. The code is rewritten below.
1 classSolution {2 Public:3listnode* Removenthfromend (listnode* head,intN) {4listnode** pre = &head;5listnode* cur =head;6 for(inti =1; I < n; i++)7cur = curNext;8 while(curnext) {9Pre = & ((*pre)next);Tencur = curNext; One } A*pre = (*pre)Next; - returnhead; - } the};
There is also a recursive solution to this problem in the answers in the above link.
1 classSolution {2 Public:3listnode* Removenthfromend (listnode* head,intN) {4 returnCountremove (head, n) = =0? HeadNext:head;5 }6 Private:7 intCountremove (listnode* node,intN) {8 if(! (node-next))returnN-1;9 intRest = countremove (node-next, N);Ten if(!rest) node-next = node-NextNext; One returnRest-1; A } -};
[Leetcode] Remove Nth Node from End of List