时间空间效率的平衡---两个链表的第一个公共结点

博客围绕找出两个链表的第一个公共结点展开。回顾相关知识点后,给出两种思路。思路一是利用Python内置字典;思路二则是先确定两链表长度,使它们达到相同起点,再同时前进判断,并给出了相应的Python代码实现。

题目描述:

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

知识点回顾:

思路:
思路1:利用Python内置的字典

Python代码实现1:

// An highlighted block
class Solution:
    def FindFirstCommonNode(self, pHead1, pHead2):
        # write code here
        tagdict ={}
        while pHead1:
            tagdict[pHead1]=True
            pHead1=pHead1.next
        while pHead2:
            if pHead2 in tagdict:
                return pHead2
            pHead2=pHead2.next

思路2:先确定两个链表的长度,然后把两个链表达到相同的起点,再同时往前走判断

python实现2:

// An highlighted block
    def FindFirstCommonNode(self, pHead1, pHead2):
        length1=length2=0
        q=pHead1
        while q:
            length1+=1
            q=q.next
        p=pHead2
        while p:
            length2+=1
            p=p.next
        length=length1-length2
        while length>0:
            pHead1=pHead1.next
            length-=1
        while length<0:
            pHead2=pHead2.next
            length+=1
        while pHead1!=pHead2:
            pHead1=pHead1.next
            pHead2=pHead2.next
        return pHead1
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值