(剑指offer)52.两个链表的第一个公共节点

输入两个链表,找出它们的第一个公共结点。
思路:
1.先遍历两个链表,计算出长度
2.让长度较长的先走 先走步数=长度差
3.然后再两个链表一起走,值相同的第一个就是两个链表第一个公共节点
时间复杂度:o(m+n)
空间复杂度:比实现两个栈的思想低。

class ListNode:
    def __init__(self, x):
        self.val = x
        self.next = None
class Solution:
    def FindFirstCommonNode(self, pHead1, pHead2):
        # write code here
        nlength1 = self.LengthListNode(pHead1)
        nlength2 = self.LengthListNode(pHead2)
        nLengthDiff = abs(nlength1-nlength2)

        if nlength1<nlength2:
            pListHeadShort = pHead1
            pListHeadLong = pHead2

        else:
            # 把相等的情况一定也要算进去
            pListHeadShort = pHead2
            pListHeadLong = pHead1


        for i in range(nLengthDiff):
            pListHeadLong = pListHeadLong.next


        while pListHeadLong and pListHeadShort and pListHeadLong!=pListHeadShort:
            pListHeadLong = pListHeadLong.next
            pListHeadShort = pListHeadShort.next

        FirstCommond = pListHeadShort
        return FirstCommond



    def LengthListNode(self,pHead):
        if pHead == None:
            return 0
        else:
            length = 0
            while pHead:
                pHead = pHead.next
                length+= 1
            return length


if __name__ == '__main__':
    node1 = ListNode(1)
    node2 = ListNode(2)
    node3 = ListNode(3)
    node1.next = node2
    node2.next = node3

    node4 = ListNode(4)
    node5 = ListNode(5)
    node4.next = node5


    node6 = ListNode(6)
    node7 = ListNode(7)


    node5.next = node6

    node6.next = node7
    node3.next = node7
    s = Solution()
    print(s.FindFirstCommonNode(node1,node4).val)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值