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