分享

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

 丹枫无迹 2022-10-16 发布于北京

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


解题思路


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

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;
    }
}

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多