Remove Nth Node From End of List
Given a linked list, remove the nth node from the end of list and return its head.
For example,
Given linked list: 1->2->3->4->5, and n = 2. After removing the second node from the end, the linked list becomes 1->2->3->5.
Note:
Given n will always be valid.
Try to do this in one pass.
需要注意当p2后移n次时,p2==Null的情况。
class Solution:
# @return a ListNode
def removeNthFromEnd(self, head, n):
p2=head;
while (n>0):
p2=p2.next
n-=1
<span style="color:#ff0000;">if p2==None:
return head.next</span>
p1=head
while p2.next:
p1=p1.next
p2=p2.next
p1.next=p1.next.next
return head