36.两个链表的第一个公共结点(python)

题目描述

输入两个链表,找出它们的第一个公共结点。
 1 class Solution:
 2     def FindFirstCommonNode(self, pHead1, pHead2):
 3         # write code here
 4         if pHead1==pHead2:
 5             return pHead1
 6         p1 = pHead1
 7         p2 = pHead2
 8         flag=1
 9         while p1 and p2 !=None:
10             p1 = p1.next
11             p2 = p2.next
12         if p1 == None:
13             flag=2
14             p1 = p2
15         k=0
16         while p1:   #计算两个链表的长度差
17             k+=1
18             p1=p1.next
19         if flag==1:  #flag记录长的那个链表
20             while k>0:
21                 pHead1=pHead1.next
22                 k-=1    #先走k步
23         else:
24             while k >0:
25                 pHead2=pHead2.next
26                 k-=1
27         while pHead1 and pHead2:
28             if pHead1==pHead2:
29                 return pHead1
30             pHead1=pHead1.next
31             pHead2=pHead2.next
32         return None

2019-12-25 10:39:02

posted @ 2019-12-25 10:40  Assange  阅读(136)  评论(0编辑  收藏  举报