剑指offer-两个链表的第一个公共结点(python)

思路一:题目求第一个公共节点,这表明,不止一个公共节点,那么先让一条链表的所有节点入栈,在遍历另一个链表,看看栈中有没有这个元素,有就说明是第一个。
思路二:可以分别让两个链表入栈,(思路就是尾部一定是一样的)。之后分别从栈中pop比较一不一样,找到第一个不一样的后面一个节点就行。
思路三,先比较两个链表,长度,长的先走几个节点,保证两个节点到各自链表尾部的长度是一样的。也不用单独开辟内存空间,一直循环下去就行。

# -*- 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
        if not pHead1 or not pHead2:
            return None
        res1=[]
        res2=[]
        cur1=pHead1
        cur2=pHead2
        while cur1:
            res1.append(cur1.val)
            cur1=cur1.next
        while cur2:
            if cur2.val in res1:
                return cur2
            cur2=cur2.next
        return None

方法三:

class Solution:
    def FindFirstCommonNode(self, pHead1, pHead2):
        # write code here
        if not pHead1 or not pHead2:
            return None
        cur1=pHead1
        cur2=pHead2
        cnt1=0
        cnt2=0
        while cur1:
            cnt1+=1
            cur1=cur1.next
        while cur2:
            cnt2+=1
            cur2=cur2.next
        node1=pHead1
        node2=pHead2
        step=abs(cnt1-cnt2)
        
        if cnt1>=cnt2:
            while step>0:
                node1=node1.next
                step-=1
        else:
            while step>0:
                node2=node2.next
                step-=1
        while node1:
            if node1==node2:
                return node1
            else:
                node2=node2.next
                node1=node1.next
        return None
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值