最容易想到的当然是类似冒泡算法,代码:
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# @param headA: the first list
# @param headB: the second list
# @return: a ListNode
def getIntersectionNode(self, headA, headB):
# Write your code here
if headA == None or headB == None:
return None
p1 = headA
p2 = headB
while p1.next != None:
while p2.next != None:
if p1 == p2:
return p1
p2 = p2.next
p2 = headB
p1 = p1.next
return None
不过不出意外地。。。超时了。
另一种方案,先找到较长的链表,然后将其向后移动|len(A) - len(B)|的距离,这样两个链表就具有相同的长度了,就不必再进行冒泡比较了,复杂度也就降为n。
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# @param headA: the first list
# @param headB: the second list
# @return: a ListNode
def getIntersectionNode(self, headA, headB):
# Write your code here
if headA == None or headB == None:
return None
p1 = headA
p2 = headB
len_a = 0
len_b = 0
while p1.next != None:
len_a += 1
p1 = p1.next
while p2.next != None:
len_b += 1
p2 = p2.next
len_c = abs(len_a - len_b)
p1 = headA
p2 = headB
if len_a >= len_b:
for i in range(len_c):
p1 = p1.next
else:
for i in range(len_c):
p2 = p2.next
while p1 != None and p2 != None:
if p1 == p2:
return p1
p1 = p1.next
p2 = p2.next
return None