@Scrazy
2017-04-11T10:01:01.000000Z
字数 586
阅读 901
python
算法
思路:
1. 求出两个链表的长度
2. 长的链表先走两步,直至俩链表一样长
3. 依次比较俩链表的每一个值
4. 相同,直接 return 否则,return None
# -*- coding:utf-8 -*-
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def FindFirstCommonNode(self, pHead1, pHead2):
if not pHead1 and pHead2:
return None
head1 = pHead1
head2 = pHead2
length1 = length2 = 0
while pHead1:
pHead1 = pHead1.next
length1 += 1
while pHead2:
pHead2 = pHead2.next
length2 += 1
if length1 > length2:
while length1 - length2:
head1 = head1.next
length1 -= 1
else:
while length2 - length1:
head2 = head2.next
length2 -= 1
while head1 and head2:
if head1 is head2:
return head1
head1 = head1.next
head2 = head2.next
return None