两个链表的第一个公共结点
2019-04-21 本文已影响0人
Haward_
题目描述
输入两个链表,找出它们的第一个公共结点。
思想:(1)借助栈
(2)先计算h1,h2的长度,让长的先走。
# -*- 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
len1,len2 = 0,0
p1,p2 = pHead1, pHead2
while p1 != None:
len1 += 1
p1 = p1.next
while p2 != None:
len2 += 1
p2 = p2.next
p1,p2 = pHead1, pHead2
t = len1 - len2
if t > 0:
while t > 0:
t -= 1
p1 = p1.next
if t < 0:
t = -t
while t > 0:
t -= 1
p2 = p2.next
while p1 != p2:
p1 = p1.next
p2 = p2.next
return p1