基本思路是使用双指针,前一个指针与后一个指针相差n个节点
class Solution:
def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:
pre = ListNode(-1,head)
dummy = pre
cur = dummy
if cur.next.next == None:
return None
if n == 1:
cur = cur.next
while cur.next is not None:
cur = cur.next
dummy = dummy.next
dummy.next = None
return pre.next
else:
while n:
cur = cur.next
n = n - 1
while cur.next is not None:
cur = cur.next
dummy = dummy.next
if dummy.next == head:
return dummy.next.next
else:
dummy.next = dummy.next.next
return pre.next
代码写的比较啰嗦,官方的解答较为简洁
class Solution:
def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
dummy = ListNode(0, head)
first = head
second = dummy
for i in range(n):
first = first.next
while first:
first = first.next
second = second.next
second.next = second.next.next
return dummy.next