class LNode:
def __init__(self):
self.data = None
self.next = None
def IsIntersect(head1, head2):
"""
方法功能:判断两个链表是否相交,如果相交找出交点
:param head1: 第一个链表
:param head2: 第二个链表
:return: 如果不相交返回None, 如果相交返回相交结点
"""
if head1 is None or head1.next is None or head2 is None or head2.next is None or head1 == head2:
return None
temp1 = head1.next
temp2 = head2.next
n1, n2 = 0, 0
# 遍历head1,找到尾结点,同时记录head1的长度
while temp1.next is not None:
temp1 = temp1.next
n1 += 1
# 遍历head2,找到尾结点,同时记录head2的长度
while temp2.next is not None:
temp2 = temp2.next
n2 += 1
if temp1 == temp2:
# 长链表线走|n1-n2|步
if n1 > n2:
while n1 - n2 > 0:
head1 = head1.next
n1 -= 1
if n2 > n1:
while n2 - n1 >0:
head2 = head2.next
n2 -= 1
# 两个链表同时前进,找出相同的结点
while head1 != head2:
head1 = head1.next
head2 = head2.next
return head1
# head1 与head2 是没有相同的尾结点
else:
return None
if __name__ == '__main__':
i = 1
# 链表头结点
head1 = LNode()
head2 = LNode()
tmp = None
cur = head1
p = None
# 构造第一个链表
while i < 8:
tmp = LNode()
tmp.data = i
cur.next = tmp
cur = tmp
if i == 5:
p = tmp
i += 1
cur = head2
# 构造第二个链表
i = 1
while i < 5:
tmp = LNode()
tmp.data = i
cur.next = tmp
cur = tmp
i += 1
# 是它们相交于点5
cur.next = p
interNode = IsIntersect(head1, head2)
if interNode is None:
print('这两个链表不相交')
else:
print('这两个链表相交点:' + str(interNode.data))
运行结果如下:
这两个链表相交点:5
本文介绍了一种用于判断两个链表是否相交,并找出交点的算法。通过比较两个链表的尾节点来确定是否相交,若相交则调整较长链表的起点,最后同步前进直至找到交点。
980

被折叠的 条评论
为什么被折叠?



