# 声明结点
class LNode():
def __init__(self):
self.data = None # 数据域
self.next = None # 指针域
# 判断两个链表是否相交
def IsIntersect(head1, head2):
if head1==None or head1.next==None or head2==None or head2.next==None or head1==head2:
return None
temp1 = head1.next
temp2 = head2.next
n1, n2 = 0, 0
# 遍历head1,找到尾结点
while temp1.next!=None:
n1 += 1
temp1 = temp1.next
# 遍历head2,找到尾结点
while temp2.next!=None:
n2 += 1
temp2 = temp2.next
if temp1.data!=temp2.data:
return None
else:
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
if __name__=="__main__":
head1 = LNode()
head2 = LNode()
cur = head1
i = 1
# 构造第一个链表
while i<8:
temp = LNode()
temp.data = i
cur.next = temp
cur = temp
if i==5:
p=temp
i += 1
# 构造第二个链表
cur = head2
i = 1
while i<5:
temp = LNode()
temp.data = i
cur.next = temp
cur = temp
i += 1
# 使他们相交于点5
cur.next = p
interNode = IsIntersect(head1, head2)
if interNode == None:
print("这两个链表不相交")
else:
print("这两个链表相交点为:"+str(interNode.data))