"Leetcode" Remove Nth Node from End of List (easy)

Source: Internet
Author: User

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.

Ideas:

The most basic way of thinking must be to use two pointers, one to walk n+1 step, then two at the same time, so the pointer must be to remove the pointer in the front of the grid.

The main problem is that if you want to delete the head node, go to the N-step of the time must be null, so to add a judgment, if you have not finished walking n+1 step encountered the first pointer to null, then return Head->next

Alas, this 1.1-point logical relationship has been dizzy for a long time. To analyze clearly before doing the problem, not every time just rely on the feeling ... The feeling is particularly unreliable at this boundary condition ...

ListNode *removenthfromend (ListNode *head,intN) {ListNode* P1 = head, * p2 =Head; N++;  while(n--//p1 Go first n+1 step {p1= p1->Next; if(P1 = = NULL && n! =0)//encountered the deletion of the head pointerreturnHead->Next; }         while(P1! =NULL)//p1 go to the end, P2 just before the pointer you want to delete {P1= p1->Next; P2= p2->Next; } P2->next = p2->next->next;//delete the specified pointerreturnHead; }

"Leetcode" Remove Nth Node from End of List (easy)

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.