面试题37. 两个链表的第一个公共结点

本文介绍了一种高效算法来查找两个链表的第一个公共节点,通过先计算两个链表的长度差,再让较长的链表先走几步,最后同步遍历两个链表直至找到公共节点,时间复杂度为O(m+n)。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

思路:
1. 首先遍历两个链表,分别求出链表的长度,下图中链表长度分别为6和4。
2. 然后p在长链表上走2步(到p’)
3. 随后p’、q从x和c同时出发,向后遍历直到找到相同的节点e。
时间复杂度为O(m+n),m,n为链表的长度。

这里写图片描述

Java 代码:

/*
public class ListNode {
    int val;
    ListNode next = null;

    ListNode(int val) {
        this.val = val;
    }
}*/
public class Solution {
    // 求链表的长度
    public static int getLength(ListNode head) {
        int length = 0;
        while(head != null) {
            head = head.next;
            length++;
        }
        return length;
    }

    public ListNode FindFirstCommonNode(ListNode head1, ListNode head2) {
        if(head1 == null || head2 == null) {
            return null;
        }
        // Step1. 第一步求出两个链表的长度 
        int len1 = getLength(head1);
        int len2 = getLength(head2);

        // Step2. 谁长谁先走
        while(len1 > len2) {
            head1 = head1.next;
            len1--;
        }

        while(len1 < len2) {
            head2 = head2.next;
            len2--;
        }

        // Step3. 两个一起走,直到公共节点
        while(head1 != null && head2 != null) {
            if(head1 == head2) {
                return head1;    
            }
            head1 = head1.next;
            head2 = head2.next;
        }
        return null;
    }
}

Python 代码:

# -*- coding:utf-8 -*-
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None
class Solution:

    def GetLength(self, head):
        length = 0
        while head:
            length += 1
            head = head.next
        return length

    def FindFirstCommonNode(self, pHead1, pHead2):
        # write code here
        len1 = self.GetLength(pHead1)
        len2 = self.GetLength(pHead2)
        while len1 > len2:
            pHead1 = pHead1.next
            len1 -= 1
        while len1 < len2:
            pHead2 = pHead2.next
            len1 += 1    
        while pHead1 and pHead1 is not pHead2:
            pHead1 = pHead1.next
            pHead2 = pHead2.next
        return pHead1

扩展题目:

求两个树节点的最低公共祖先

这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值