一、题目
编写一个程序,找到两个单链表相交的起始节点。
二、思路
A和B两个链表长度可能不同,但是A+B和B+A的长度是相同的,所以遍历A+B和遍历B+A一定是同时结束。
如果A,B相交的话A和B有一段尾巴是相同的,所以两个遍历的指针一定会同时到达交点 如果A,B不相交的话两个指针就会同时到达A+B(B+A)的尾节点。
三、题解
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
def make_list(arr):
head_node = None
p_node = None
for a in arr:
new_node = ListNode(a)
if head_node is None:
head_node = new_node
p_node = new_node
else:
p_node.next = new_node
p_node = new_node
return head_node
# def print_list(head):
# while head is not None:
# print(head.val, end=',')
# head = head.next
class Solution:
def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode:
# curr1指向链表A的头结点,curr2指向链表B的头结点
curr1, curr2 = headA, headB
while curr1 != curr2:
# curr1 = curr1.next if curr1 else headB
if curr1:
curr1 = curr1.next
else:
# 当 curr1 到达链表的尾部时,将它重定位到链表 B 的头结点
curr1 = headB
# curr2 = curr2.next if curr2 else headA
if curr2:
curr2 = curr2.next
else:
# 当 curr2 到达链表的尾部时,将它重定位到链表 A 的头结点。
curr2 = headA
return curr1
"""
A和B两个链表长度可能不同,但是A+B和B+A的长度是相同的,所以遍历A+B和遍历B+A一定是同时结束。
如果A,B相交的话A和B有一段尾巴是相同的,所以两个遍历的指针一定会同时到达交点 如果A,B不相交的话两个指针就会同时到达A+B(B+A)的尾节点
"""
s = Solution()
a = [4,1,8,4,5]
b = [5,6,1,8,4,5]
head_a = make_list(a)
head_b = make_list(b)
# 在8处相交
head_a.next.next = head_b.next.next.next
# print_list(head_a)
# print_list(head_b)
print(s.getIntersectionNode(head_a,head_b))
时间复杂度 : O(m+n)
空间复杂度 : O(1)