题解 | #两个链表的第一个公共结点#
两个链表的第一个公共结点
http://www.nowcoder.com/practice/6ab1d9a29e88450685099d45c9e31e46
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
#
#
# @param pHead1 ListNode类
# @param pHead2 ListNode类
# @return ListNode类
#
class Solution:
def FindFirstCommonNode(self , pHead1 , pHead2 ):
# write code here
tmp1=pHead1
tmp2=pHead2
while tmp1 and tmp2:
if tmp1==tmp2:
return tmp2
tmp1=tmp1.next
tmp2=tmp2.next
if tmp1:
k=0
while tmp1:
tmp1=tmp1.next
k+=1
tmp1=pHead1
tmp2=pHead2
for i in range(k):
tmp1=tmp1.next
while tmp1!=tmp2:
if tmp1==tmp2:
return tmp2
tmp1=tmp1.next
tmp2=tmp2.next
return tmp1
if tmp2:
k=0
while tmp2:
tmp2=tmp2.next
k+=1
tmp2=pHead2
tmp1=pHead1
for i in range(k):
tmp2=tmp2.next
while tmp2!=tmp1:
tmp2=tmp2.next
tmp1=tmp1.next
return tmp2