解题思路
第一步:前指针先走n步
第二步:然后前后指针一起走
第二步过程中,后指针指向target,需要保存指向target的指针prev以便随后删除
https://leetcode-cn.com/problems/remove-nth-node-from-end-of-list/
代码
# 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
"""
pt = prev = tgt = head
while n > 0:
pt = pt.next
n -= 1
while pt:
pt = pt.next
prev = tgt
prev, tgt = tgt, tgt.next
if tgt == head:
head = tgt.next
else:
prev.next = tgt.next
return head