457 字
2 分钟
代码随想录算法训练营第四天 | 链表 Part02
链表基础
24. 两两交换链表中的节点
class Solution: def swapPairs(self, head: Optional[ListNode]) -> Optional[ListNode]: dummy = ListNode(next = head) cur = dummy # 由于是两两交换,所以需要至少两个节点才能进行交换 # 当 cur.next 和 cur.next.next 都存在时,才进行交换 while cur.next and cur.next.next: # temp1 => 准备交换的第一个节点 temp1 = cur.next # temp1 => temp1.next => temp2 temp2 = cur.next.next.next cur.next = temp1.next temp1.next.next = temp1 temp1.next = temp2 cur = temp1 return dummy.next
19. 删除链表的倒数第 N 个节点
class Solution: def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]: dummy = ListNode(next=head) fast = slow = dummy # fast 先走 n+1 步,这样 fast 和 slow 之间的距离为 n for _ in range(n + 1): fast = fast.next
# 当 fast 到达链表末尾时,slow 的下一个节点就是要删除的节点 while fast: fast = fast.next slow = slow.next
# 删除节点 slow.next = slow.next.next return dummy.next
面试题02.07.链表相交
class Solution: def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode: l1, l2 = headA, headB # 当 l1 和 l2 相等时,有两种情况:1. 相交节点;2. 都为 None while l1 != l2: if not l1: l1 = headB else: l1 = l1.next if not l2: l2 = headA else: l2 = l2.next # 返回相交节点或 None return l1
142. 环形链表 II
class Solution: def detectCycle(self, head: Optional[ListNode]) -> Optional[ListNode]: fast, slow = head, head # 当快指针为None 或者快指针的下一个节点为 None 时,说明链表没有环 while fast and fast.next: fast = fast.next.next slow = slow.next # 当快慢指针相遇时,说明链表有环,接下来就需要找到环的入口节点 if fast == slow: fast = head # 当第二次快慢指针相遇时,slow 就是环的入口节点 while fast != slow: fast = fast.next slow = slow.next return slow return None
代码随想录算法训练营第四天 | 链表 Part02
https://fuwari.vercel.app/posts/code_musings_day_four/