打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
两个链表的第一个公共结点

输入两个链表,找出它们的第一个公共结点(保证一定存在公共结点)


解题思路


假设两个链表结构如图所示,最简单的想法就是:让长的链表先走,走完两个链表的长度差,然后再一起走

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);
        
        ListNode curNode1 = pHead1;
        ListNode curNode2 = pHead2;
        
        if(length1 >= length2) {
            int len = length1 - length2;
            while(len > 0) {
                curNode1 = curNode1.next;
                len--;
            }
        }
        
        if(length2 > length1) {
            int len = length2 - length1;
            while(len > 0) {
                curNode2 = curNode2.next;
                len--;
            }
        }
        
        while(curNode1 != curNode2) {
            curNode1 = curNode1.next;
            curNode2 = curNode2.next;
        }
        
        return curNode1;
    }
    
    public int getLength(ListNode pHead) {
        int count = 0;
        ListNode curNode = pHead;
        while(curNode != null) {
            count++;
            curNode = curNode.next;
        }
        return count;
    }
}

上一种做法使用了差值来让链表长度相同,也可以用别的方法。假设链表 A 长度为 a, 链表 B 的长度为 b,此时 a != b,但是,a + b == b + a


public class Solution {
    
    public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
        ListNode curNode1 = pHead1;
        ListNode curNode2 = pHead2;
        while(curNode1 != curNode2) {
            curNode1 = curNode1 == null ? pHead2 : curNode1.next;
            curNode2 = curNode2 == null ? pHead1 : curNode2.next;
        }
        return curNode1;
    }
}

也可以运用 HashMap 的特性帮助解题

import java.util.HashMap;
public class Solution {
    public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
        ListNode curNode1 = pHead1;
        ListNode curNode2 = pHead2;
        HashMap<ListNode, Integer> hashMap = new HashMap<ListNode, Integer>();
        while (curNode1 != null) {
            hashMap.put(curNode1, null);
            curNode1 = curNode1.next;
        }
        while (curNode2 != null) {
            if (hashMap.containsKey(curNode2))
                return curNode2;
            curNode2 = curNode2.next;
        }
        return null;
    }
}

本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
剑指offer 36 两个链表的第一个公共结点
链表中环的入口结点
LeetCode实战:合并K个排序链表
删除链表中重复的结点
459. 删除链表的倒数第N个节点的3种方式
算法46(两个单向链表,找出它们的第一个公共结点。)
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服