剑指offer python版 两个链表的第一个公共结点
class ListNode(object): def __init__(self,x): self.val=x self.next=None class Link(object): def __init__(self,values=None): self.nodes=self.set_link(values) if values else None def get_link(self): return self.nodes def set_link(self,values): if not values : return False head=ListNode(0) move=head try: for i in values: tmp=ListNode(i) move.next=tmp move=move.next except Exception as e: print(e) return head.next def aa(link1, link2): if not link1 or not link2: return None length1 = length2 = 0 move1, move2 = link1, link2 while move1: # 获取链表长度 length1 += 1 move1 = move1.next while move2: length2 += 1 move2 = move2.next while length1 > length2: # 长链表先走多的长度 length1 -= 1 link1 = link1.next while length2 > length1: length2 -= 1 link2 = link2.next while link1: # 链表一起走 if link1 == link2: return link1 link1, link2 = link1.next, link2.next return None a=Link([1,2,3,3,4,4]) b=Link([3,6,3,2]) m=a.get_link() q=b.get_link() print(aa(m,q)) def aa(head1,head2): if not head1 or not head2: return False link1=0 link2=0 move1=head1 move2=head2 while move1: link1 +=1 move1=move1.next while move2: link2 +=1 move2=move2.next m=link1-link2 if m>0: while m>0: head1=head1.next m -=1 else: while m<0: head2=head2.next m +=1 while head1: if head1==head2: return head1 head1=head1.next head2=head2.next return None