剑指offer-题37:两个链表的第一个公共节点

本文介绍两种寻找两个链表首个公共节点的方法,并提供Java和Python实现代码。一种方法通过计算链表长度来同步遍历查找,另一种使用栈来逆向比较节点。

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

题目描述

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

实验平台:牛客网


解决思路:

这题书上列举了两个可行的解法,分别如下

解法一

这里写图片描述

解法二

这里写图片描述
这里写图片描述

其中解法二我是用java实现的,解法一我用python3实现。跟解法二相比,解法一需要另外两个列表当做栈,相当于用空间换了时间。具体代码如下

java:

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

    ListNode(int val) {
        this.val = val;
    }
}*/
public class Solution {
    public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
        int list1Length = getListLength(pHead1);
        int list2Length = getListLength(pHead2);
        ListNode longList = null;
        ListNode shortList = null;
        int diff;
        if (list1Length >= list2Length) {
            longList = pHead1;
            shortList = pHead2;
            diff = list1Length - list2Length;
        } else {
            longList = pHead2;
            shortList = pHead2;
            diff = list2Length - list1Length;
        }

        for (int i = 0; i < diff; i++) {
            longList = longList.next;
        }

        while (longList != null && shortList != null & longList != shortList) {
            longList = longList.next;
            shortList = shortList.next;
        }

        if (longList == shortList) {
            return longList;
        } else {
            return null;
        }
    }

    public int getListLength(ListNode node) {
        int length = 0;
        while (node != null) {
            length++;
            node = node.next;
        }
        return length;
    }
}

python:

# -*- 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
        stack1 = []
        stack2 = []
        common_node = None
        while pHead1 is not None:
            stack1.append(pHead1)
            pHead1 = pHead1.next
        while pHead2 is not None:
            stack2.append(pHead2)
            pHead2 = pHead2.next
        while len(stack1) > 0 and len(stack2) > 0 and stack1[-1] == stack2[-1]:
            common_node = stack1[-1]
            stack1.pop()
            stack2.pop()
        return common_node
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值