[Leetcode] Remove Nth Node from End of List

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.