# @lc code=start # Definition for singly-linked list. # class ListNode(object): # def __init__(self, val=0, next=None): # self.val = val # self.next = next classSolution(object): defreverseBetween(self, head, left, right): """ :type head: ListNode :type left: int :type right: int :rtype: ListNode """ ## 思路:从头开始扫描并记录位置,当位置到达left时进行头插法,直到到达right位置。
if left == right: return head pre = head ## pre记录left的前一个节点 node = head ## node用于遍历 position = 1## 记录位置 ## 找到left位置的节点 while position != left: pre = node node = node.next position += 1 ## 特殊情况判断 if position == 1: pre = ListNode(502)
tail = node ## tail记录逆转的尾节点 post = node ## post记录头插法位置的后一节点 ## 找到开始头插法的节点 node = node.next position += 1 ## 循环进行头插法,直到到达right的节点 while position <= right: pre.next = node node = node.next pre.next.next = post post = pre.next position += 1 ## 逆转的尾节点连接到后面的节点 tail.next = node ## 特殊情况判断 if pre.val == 502: head = pre.next pre.next = None return head
输出:Reference of the node with value = 8 输入解释:相交节点的值为 8 (注意,如果两个链表相交则不能为 0)。从各自的表头开始算起,链表 A 为 [4,1,8,4,5],链表 B 为 [5,0,1,8,4,5]。在 A 中,相交节点前有 2 个节点;在 B 中,相交节点前有 3 个节点。
# @lc code=start # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None
classSolution: defdetectCycle(self, head: ListNode) -> ListNode: """ 思路: 1. 快慢指针(快指针一次走两步,慢指针一次走一步)相遇时,记录该相遇节点; 2. 从头head处出发另一个慢指针和当前在meet节点的慢指针同时出发,直到两者相遇,便是入口节点。 解释:假设入口前的一段长为a,慢指针从环入口到与快指针相遇位置为b,环长度为c; 那么,快慢指针相遇时:快指针走的路程(a+b+c) = 慢指针走的路程的两倍(2*(a+b)); 由上式得出:a + b = c。所以,从相遇位置到环入口与a(入口前的一段)距离相等, 所以慢指针和从头开始的指针这时同时出发的相遇节点就是入口。 """ fast = head slow = head meet = None while fast != None: slow = slow.next fast = fast.next if fast == None: returnNone fast = fast.next if fast == slow: meet = slow break if meet == None: returnNone while meet != Noneand head != None: if meet == head: return meet head = head.next meet = meet.next returnNone
—————
2.5 复制带随机指针的链表(138. 复制带随机指针的链表)
给你一个长度为 n 的链表,每个节点包含一个额外增加的随机指针 random ,该指针可以指向链表中的任何节点或空节点。
构造这个链表的 深拷贝。 深拷贝应该正好由 n 个 全新 节点组成,其中每个新节点的值都设为其对应的原节点的值。新节点的 next 指针和 random 指针也都应指向复制链表中的新节点,并使原链表和复制链表中的这些指针能够表示相同的链表状态。复制链表中的指针都不应指向原链表中的节点 。
例如,如果原链表中有 X 和 Y 两个节点,其中 X.random --> Y 。那么在复制链表中对应的两个节点 x 和 y ,同样有 x.random --> y 。
返回复制链表的头节点。
用一个由 n 个节点组成的链表来表示输入/输出中的链表。每个节点用一个 [val, random_index] 表示:
# @lc code=start # Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next from typing import List