# 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]:
point1=headA
p=False
while True:
point2=headB
while True:
if point1==point2:
p=True
return point2
break
point2=point2.next
if point2==None:
break
point1=point1.next
if point1==None:
break
if p==False:
return None
暴力求解超时了,break可以做while的中断,while True是无限循环。
# 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=[]
while True:
a.append((headA,headA.next))
headA=headA.next
if headA is None:
break
while True:
if (headB,headB.next) in a:
return headB
headB=headB.next
if headB is None:
break