题目描述
方法:
1. 快慢指针遍历+删除
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:
slow = fast = head
while n>0:
fast = fast.next
n -= 1
pre = ListNode(0)
pre.next = slow
while fast:
fast = fast.next
slow = slow.next
pre = pre.next
pre.next = slow.next
return head if slow != head else pre.next
注意:判断slow!=head不够优雅
2. 用新的dump=pre来解决删除head时的情况
ps:pre=dump,pre.next改变,dump.next跟着改变
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:
slow = fast = head
while n>0:
fast = fast.next
n -= 1
dump = pre = ListNode(0)
pre.next = slow
while fast:
fast = fast.next
slow = slow.next
pre = pre.next
pre.next = slow.next
return dump.next