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.
使用两个指针,两个指针相隔n-1,每次两个指针向后一步,当后面一个指针没有后继了,前面一个指针就是要删除的节点 注意:可能会出现只有1个节点,同时n=1的情况,这时指针没有后继节点
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def removeNthFromEnd(self, head, n):
"""
:type head: ListNode
:type n: int
:rtype: ListNode
"""
"""
采用双指针思想,两个指针相隔n-1,每次两个指针向后一步,当后面一个指针没有后继了,前面一个指针就是要删除的节点
"""
p = head
q = head
Ppre = None
for x in xrange(0, n-1):
q = q.next
while q.next is not None:
Ppre = p
p = p.next
q = q.next
# 出现[1],n=1的情况下,Ppre依然为None
if Ppre == None:
head = p.next
else:
Ppre.next = p.next
return head