2024/11/27 【链表】LeetCode 24 两两交换链表中的节点 & LeetCode 19 删除链表的倒数第N个节点
递归方式:没有想到
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def swapPairs(self, head: Optional[ListNode]) -> Optional[ListNode]: if head is None or head.next is None: return head pre = head cur = head.next next = head.next.next cur.next = pre pre.next = self.swapPairs(next) return cur
19. 删除链表的倒数第 N 个结点 - 力扣(LeetCode)
代码随想录给出的一次遍历的双指针法,没有想到
# 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]: dummy_head = ListNode(next=head) slow = fast = dummy_head for i in range(n+1): fast = fast.next while fast: slow = slow.next fast = fast.next slow.next = slow.next.next return dummy_head.next
需要理解为什么快指针先走n+1步🌟
推出快指针先走 n+1
步是为了在链表中为慢指针和快指针之间创建一个“间隔”,这个间隔的长度恰好等于 n
(如果我们考虑的是从快指针停止后,慢指针指向的位置到快指针停止时所在位置之间的节点数,不包括慢指针指向的节点)。这样做的目的是为了让慢指针能够在快指针到达链表末尾时,精确地指向倒数第 n+1
个节点。