美文网首页
两个链表的第一个公共结点

两个链表的第一个公共结点

作者: Haward_ | 来源:发表于2019-04-21 23:37 被阅读0次

    题目描述
    输入两个链表,找出它们的第一个公共结点。

    思想:(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
                
            
    

    相关文章

      网友评论

          本文标题:两个链表的第一个公共结点

          本文链接:https://www.haomeiwen.com/subject/qtasgqtx.html