offer-37两个链表是否相交,找第一个公共节点

时间:2022-10-25 11:01:10
# coding=utf-8
'''
两个链表是否相交,找第一个公共节点,必知两个链表相交则尾部一定相等,所以长链表先走两个链表长度之差的长度,然后两个指针再一起走
'''
class ListNode():
def __init__(self,x):
self.val=x
self.next=None

def findcommon(p1,p2):
n1=countlength(p1)
n2=countlength(p2)
if n1<=0 or n2<=0:
return 0
phead1=p1
phead2=p2
if n1>=n2:
for i in range(n1-n2):
phead1=phead1.next
else:
for i in range(n2-n1):
phead2=phead2.next
while phead1!=None and phead2!=None:
phead1=phead1.next
phead2=phead2.next
if phead1==phead2:
return phead1

def countlength(p):
if p==None:
return -1
phead=p
leng=0
while phead.next!=None:
phead=phead.next
leng+=1
return leng
if __name__ == '__main__':
node1=ListNode(0)
node2=ListNode(3)
node3=ListNode(4)
node4=ListNode(5)
node1.next=node2
node2.next=node3
node3.next=node4
node5=ListNode(1)
node6=ListNode(2)
node7=ListNode(3)
node8=ListNode(4)
node9=ListNode(5)
node5.next=node6
node6.next=node7
node7.next=node8
node8.next=node9
print(findcommon(node1,node5))