剑指offer-36.两个链表的第一个公共结点-Python

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

题目描述

输入两个链表,找出它们的第一个公共结点。(注意因为传入数据是链表,所以错误测试数据的提示是用其他方式显示的,保证传入数据是正确的)

记录

公共节点:单链表,该节点及其之后的节点都相同。

方法一:
指针。

  1. 有公共节点
    在这里插入图片描述
  2. 无公共节点
    同时为空,不会陷入死循环。
    在这里插入图片描述
# -*- 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
        p1 = pHead1
        p2 = pHead2
        while p1 != p2:
            if p1 == None:
                p1 = pHead2
            else:
                p1 = p1.next
            if p2 == None:
                p2 = pHead1
            else:
                p2 = p2.next
        return p2

备注:先遍历两个链表,统计长度。让长链表先走相差的步,然后再对两个链表进行遍历匹配,遇到的第一个相同节点就是公共节点。

方法二:

最后一个相等的节点就是第一个公共节点。

class Solution:
    def FindFirstCommonNode(self, pHead1, pHead2):
        # write code here
        stack1 = []
        stack2 = []
        while pHead1:
            stack1.append(pHead1)
            pHead1 = pHead1.next
        while pHead2:
            stack2.append(pHead2)
            pHead2 = pHead2.next
        res = None
        while stack1 and stack2:
            p1 = stack1.pop()
            p2 = stack2.pop()
            if p1 == p2:
                res = p1
            else:
                break
        return res

方法三:
set()
讨论中看见的。

class Solution:
    def FindFirstCommonNode(self, pHead1, pHead2):
        # write code here
        res = set()
        while pHead1:
            res.add(pHead1)
            pHead1 = pHead1.next
        while pHead2:
            if pHead2 in res:
                return pHead2
            pHead2 = pHead2.next

tips

有环或无环?
参考

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值