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

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

解题思路:如果两个链表有公共节点,那么这两个链表从某一节点开始,它们的next都指向同一个节点,之后它们所有的节点都是重合的,不可能再出现分叉。所以拓扑形状看起来是Y型。
首先遍历两个链表得到它们的长度,比较链表的长度,以及长的链表比短的链表多几个节点。在第二次遍历的时候,先在较长的节点上走若干步,接着同时在两个链表上遍历,找到的第一个相同的节点就是它们的公共的节点。

    public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
        if (pHead1 == null || pHead2 == null) {
            return null;
        }
        int len1 = getLenOfList(pHead1);
        int len2 = getLenOfList(pHead2);
        int difLen = Math.abs(len1 - len2);
        // 先在长链表上走几步,再同时在两个链表上遍历。
        ListNode p1 = pHead1;
        ListNode p2 = pHead2;
        if (len1 > len2) {
            for (int i = 0; i < difLen; i++) {
                p1 = p1.next;
            }
        } else {
            for (int i = 0; i < difLen; i++) {
                p2 = p2.next;
            }
        }
        while (p1 != null && p2 != null && p1 != p2) {
            p1 = p1.next;
            p2 = p2.next;
        }
        return p1;

    }

    public static int getLenOfList(ListNode head) {
        int count = 0;
        ListNode p = head;
        while (p != null) {
            count++;
            p = p.next;
        }
        return count;
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值