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

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

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

/*
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 diff = diff(pHead1, pHead2);
        if(diff > 0) {
            while(diff > 0) {
                pHead1 = pHead1.next;
                diff--;
            }
        } else {
            while(diff < 0) {
                pHead2 = pHead2.next;
                diff++;
            }
        }
        while(pHead1 != null && pHead2 != null) {
            if(pHead1 == pHead2) return pHead1;
            pHead1 = pHead1.next;
            pHead2 = pHead2.next;
        }
        return null;

    }

    private int diff(ListNode l1, ListNode l2) {
        int length1 = 0;
        int length2 = 0;
        while(l1.next != null) {
            length1++;
            l1 = l1.next;
        }
        while(l2.next != null) {
            length2++;
            l2 = l2.next;
        }
        return length1 - length2;
    }
}

全部评论

相关推荐

刷牛客的我很豁达:你是不是对算法有什么误解,你没手握两篇顶刊顶会,还想搞算法岗,有顶刊顶会在算法岗算才入门
点赞 评论 收藏
分享
昨天 11:08
已编辑
上海大学 Java
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务