力扣 160. 相交链表

前置

1
2
3
4
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next

解法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
def getIntersectionNode(headA, headB):
a, countA, b, countB = headA, 0, headB, 0
while a:
countA += 1
a = a.next
while b:
countB += 1
b = b.next
# print(countA, countB)
if countA > countB:
c, cur, other = countA - countB, headA, headB
else:
c, cur, other = countB - countA, headB, headA
while c > 0:
cur = cur.next
c -= 1

while cur != other:
cur = cur.next
other = other.next

return cur
  • Copyright: Copyright is owned by the author. For commercial reprints, please contact the author for authorization. For non-commercial reprints, please indicate the source.
  • Copyrights © 2022 eightyninth
  • Visitors: | Views:

请我喝杯咖啡吧~

支付宝
微信