给你一个链表,删除链表的倒数第 n 个结点,并且返回链表的头结点。 进阶:你能尝试使用一趟扫描实现吗?
输入:head = [1,2,3,4,5], n = 2 输出:[1,2,3,5] 示例 2: 输入:head = [1], n = 1 输出:[] 示例 3: 输入:head = [1,2], n = 1 输出:[1]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next classSolution: defremoveNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]: dummy_head = ListNode(next=head) slow = dummy_head fast = dummy_head n += 1 while n and fast : n -= 1 fast = fast.next while fast: fast = fast.next slow = slow.next slow.next = slow.next.next return dummy_head.next
classSolution: defdetectCycle(self, head: Optional[ListNode]) -> Optional[ListNode]: fast = head slow = head while fast and fast.next: fast = fast.next.next slow = slow.next if slow == fast: index = slow index_s = head while index != index_s: index = index.next index_s = index_s.next return index returnNone
classSolution: defdetectCycle(self, head: Optional[ListNode]) -> Optional[ListNode]: fast = head slow = head while fast and fast.next: fast = fast.next.next slow = slow.next if slow == fast: fast = head while slow != fast: slow = slow.next fast = fast.next return fast returnNone