会超出时间限制:
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
标签:ListNode,cur,leedcode,相交,next,链表,headB,headA From: https://www.cnblogs.com/yyyjw/p/18049153