两个链表的第一个公共结点
题目描述
输入两个链表,找出它们的第一个公共结点。
python solution:
# -*- coding:utf-8 -*-
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def FindFirstCommonNode(self, pHead1, pHead2):
if pHead2 is None or pHead1 is None:
return None
work1,work2 = pHead1,pHead2
l1,l2 = 1,1
while work1.next:
work1 = work1.next
l1 += 1
while work2.next:
work2 = work2.next
l2 += 1
path = abs(l1-l2)
if l1<l2:
pHead1,pHead2 = pHead2,pHead1
for i in range(path):
pHead1 = pHead1.next
while pHead1!=pHead2:
pHead1 = pHead1.next
pHead2 = pHead2.next
return pHead2