题解 | #两个链表的第一个公共结点#

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

https://www.nowcoder.com/practice/6ab1d9a29e88450685099d45c9e31e46

import java.util.*;
/*
public class ListNode {
    int val;
    ListNode next = null;

    ListNode(int val) {
        this.val = val;
    }
}*/
public class Solution {
    public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
        if (pHead1 == null || pHead2 == null) {
            return null;
        }

        // 计算两个链表的长度
        int length1 = getLength(pHead1);
        int length2 = getLength(pHead2);

        // 移动长链表的指针,使其与短链表的指针在同一起点
        while (length1 > length2) {
            pHead1 = pHead1.next;
            length1--;
        }
        while (length2 > length1) {
            pHead2 = pHead2.next;
            length2--;
        }

        // 同时移动两个指针,直到找到公共节点
        while (pHead1 != null && pHead2 != null) {
            if (pHead1 == pHead2) {
                return pHead1;
            }
            pHead1 = pHead1.next;
            pHead2 = pHead2.next;
        }

        return null; // 没有找到公共节点
    }

    // 计算链表的长度
    private int getLength(ListNode head) {
        int length = 0;
        while (head != null) {
            length++;
            head = head.next;
        }
        return length;
    }
}

这个实现方式首先计算两个链表的长度,然后移动长链表的指针,使其与短链表的指针在同一起点。接着,同时移动两个指针,直到找到第一个公共节点。

需要注意的是,如果两个链表没有公共节点,最终会同时移动到末尾,返回 null。否则,返回找到的第一个公共节点。

这个实现方式的关键在于通过计算链表长度的差值,将两个链表的指针调整到同一起点,然后同步移动指针,找到公共节点。

全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务