题目描述
输入两个链表,找出它们的第一个公共结点。
# -*- coding:utf-8 -*-
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def FindFirstCommonNode(self, pHead1, pHead2):
# write code here
l1 = l2 = 0
r1, r2 = pHead1, pHead2
while r1:
r1 = r1.next
l1 += 1
while r2:
r2 = r2.next
l2 += 1
r1, r2 = pHead1, pHead2
if l1>l2:
for _ in range(l1-l2): r1=r1.next
else:
for _ in range(l2-l1): r2=r2.next
while r1!=r2:
r1, r2 = r1.next, r2.next
return r1
网友评论