leedcode 相交链表
会超出时间限制:
class Solution: def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> Optional[ListNode]: cur_b=headB cur_a=headA while cur_b!=None: #两个相等 if cur_b==cur_a: return cur_a else: if cur_a==None: cur_b=cur_b.next cur_a=headA else: cur_a=cur_a.next
gpt改进:
class Solution: def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> Optional[ListNode]: # 初始化两个指针分别指向链表头 cur_a, cur_b = headA, headB count=0 while cur_a != cur_b: # 遍历链表A,如果已经到达末尾,则将指针重置到链表B的头部 if cur_a: cur_a = cur_a.next else: cur_a = headB # 遍历链表B,如果已经到达末尾,则将指针重置到链表A的头部 if cur_b: cur_b = cur_b.next else: cur_b = headA count+=1 # 返回相交节点或None(如果没有相交节点) print(count) return cur_a
另一种思路,先单独移动链表长度较长的指针,来使两个指针同步:
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> Optional[ListNode]: # 计算链表A和链表B的长度 len_a = self.cal_len(headA) len_b = self.cal_len(headB) # 初始化两个指针分别指向链表头 cur_a, cur_b = headA, headB # 如果链表A的长度大于等于链表B的长度 if len_a >= len_b: diff_val = len_a - len_b # 将链表A的指针移动到与链表B长度相同的位置 while diff_val > 0: cur_a = cur_a.next diff_val -= 1 else: # 如果链表B的长度大于链表A的长度 diff_val = len_b - len_a # 将链表B的指针移动到与链表A长度相同的位置 while diff_val > 0: cur_b = cur_b.next diff_val -= 1 # 此时,cur_a 和 cur_b 处于相同的相对位置 # 如果它们相等,说明找到了交点 if cur_a == cur_b: return cur_a # 否则,继续同时移动两个指针直到找到交点或到达链表末尾 while cur_a != cur_b: cur_a = cur_a.next cur_b = cur_b.next # 如果找到交点,返回交点 if cur_a == cur_b: return cur_a # 如果没有找到交点,返回None return None def cal_len(self, head): count = 0 cur = head # 计算链表的长度 while cur != None: cur = cur.next count += 1 return count

浙公网安备 33010602011771号