LeetCode19 Remove Nth Node from End of List

Source: Internet
Author: User

Test instructions

Given A linked list, remove the nth node from the end of the list and return its head.

For example,

   n = 2.   After removing the second node from the end, the linked list becomes 1->2->3->5.

Try to do the in one pass. (easy)


Analysis: Although the topic is easy, but with one pass to do it still contains a few linked lists commonly used techniques, have reference value;

There is nothing difficult on the list algorithm, it is the code carefully, and then familiar with several processing methods.

1.Two pointers. The use of quick and slow hands, fast hands first walk n steps, and then go together, fast next to the end, slow to get to delete the previous bit;

2. Dummy node. The head position may be deleted, the problem is returned, and the return problem is handled with dummy node.

Code:

1 /**2 * Definition for singly-linked list.3 * struct ListNode {4 * int val;5 * ListNode *next;6 * ListNode (int x): Val (x), Next (NULL) {}7  * };8  */9 classSolution {Ten  Public: Onelistnode* Removenthfromend (listnode* head,intN) { AListNode Dummy (0); -Dummy.next =head; -Head = &dummy; thelistnode* chaser =head; -Listnode* runner =head; -          for(inti =0; I < n; ++i) { -Runner = RunnerNext; +         } -          while(Runner-Next! =nullptr) { +Runner = RunnerNext; AChaser = ChaserNext; at         } -listnode* temp = ChaserNext; -Chaser next = Chaser, NextNext; -         Deletetemp; -         returnDummy.next; -     } in};

LeetCode19 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.