双指针解法
通过两个指针slow,fast可以很方便的解决这个问题。我们记录一个快指针,一个慢指针,slow指针起始点是链表头部,fast指针起始点为n。随即两个指针同时开始往下走,当fast走到链表末尾的时候,slow指针的下一个指针就是l-n,也就是倒数第n个节点。slow.next = slow.next.next删除即可。
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
dummy = ListNode(None)
dummy.next = head
slow = dummy
fast = dummy
for i in range(n+1):
slow = slow.next
while slow != None:
slow = slow.next
fast = fast.next
fast.next = fast.next.next
return dummy.next