Leetcode "Remove Nth Node from End of List" Python implementation

Source: Internet
Author: User

title :

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.

Note:
Given n would always be valid.
Try to do the in one pass.

code : OJ online test via runtime:188 ms

1 #Definition for singly-linked list.2 #class ListNode:3 #def __init__ (self, x):4 #self.val = x5 #Self.next = None6 7 classSolution:8     #@return a ListNode9     defremoventhfromend (self, head, N):Ten         ifHead isNone: One             returnHead A              -Dummyhead =listnode (0) -Dummyhead.next =Head theP1 =Dummyhead -P2 =Dummyhead -          -          forIinchRange (0,n): +P1 =P1.next -          +          whileP1.next is  notNone: AP1 =P1.next atP2 =P2.next -             ifP1.next isNone: -                  Break -          -P2.next =P2.next.next -          in         returnDummyhead.next

Ideas :

Linked list basically need a virtual table header, the main idea of this problem is a double pointer

Let the first pointer P1 go first n, then let P1 and P2 go together, and when P1 goes to the last element of the list, P2 goes to the bottom of the n+1 element, and P2.next jumps to the end of the table.

Note that the judging condition is that p1.next is not none, so it is a protection to judge whether the P1.next is none in the while loop.

Another is to pay attention to the situation of special case, the small white my habit is at the beginning of such cases are judged out, may sacrifice the simplicity of the code, there is great God passing also please make brick pointing.

Leetcode "Remove Nth Node from End of List" Python implementation

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.