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

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

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) {
        int length1 = ListNodeLength(pHead1);
        int length2 = ListNodeLength(pHead2);
        
        if (length1 > length2) {
            pHead1 = WalkListNode(pHead1, length1 - length2);
        } else {
            pHead2 = WalkListNode(pHead2, length2 - length1);
        }
        
        while (pHead1 != null) {
            if (pHead1 == pHead2) return pHead1;
            pHead1 = pHead1.next;
            pHead2 = pHead2.next;
        }

        return null;
    }
    public int ListNodeLength(ListNode pHead) {
        int size = 0;
        while (pHead != null) {
            size++;
            pHead = pHead.next;
        }
        return size;
    }
    public ListNode WalkListNode(ListNode pHead, int step) {
        for (int i = 0; i < step; i++) {
            pHead = pHead.next;
        }
        return pHead;
    }
}

计算各自链表长度以及长度差距。

共同链表节点的特点是首个节点相同,后续到尾节点的链节点都是共同的,也就是只需关心首个是否为共同节点即可。

先计算节点数量差距,去除首节点数,直到两链表相互相同数量,然后两两对比进行查找。

全部评论

相关推荐

MScoding:你这个实习有一个是当辅导老师,这个和找技术岗没有关系吧?
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务