交叉链表求交点
1 class ListNode: 2 def __init__(self, x): 3 self.val = x 4 self.next = None 5 def node(l1, l2): 6 length1, lenth2 = 0, 0 7 # 求两个链表长度 8 while l1.next: 9 l1 = l1.next 10 length1 += 1 11 while l2.next: 12 l2 = l2.next 13 length2 += 1 14 # 长的链表先走 15 if length1 > lenth2: 16 for _ in range(length1 - length2): 17 l1 = l1.next 18 else: 19 for _ in range(length2 - length1): 20 l2 = l2.next 21 while l1 and l2: 22 if l1.next == l2.next: 23 return l1.next 24 else: 25 l1 = l1.next 26 l2 = l2.next
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
def node(l1, l2):
length1, lenth2 = 0, 0
# 求两个链表长度
while l1.next:
l1 = l1.next
length1 += 1
while l2.next:
l2 = l2.next
length2 += 1
# 长的链表先走
if length1 > lenth2:
for _ in range(length1 - length2):
l1 = l1.next
else:
for _ in range(length2 - length1):
l2 = l2.next
while l1 and l2:
if l1.next == l2.next:
return l1.next
else:
l1 = l1.next
l2 = l2.next