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

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

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) {
        ListNode cur1 = pHead1;
        ListNode cur2 = pHead2;

        int list1 = getListLength(cur1);
        int list2 = getListLength(cur2);

        int dis = Math.abs(list1 - list2);

        ListNode longlist = list1 > list2 ? pHead1 : pHead2;
        ListNode shortlist = list1 > list2 ? pHead2 : pHead1;

        for(int i = 0; i < dis; i++){
            longlist = longlist.next;
        }

        while(longlist != shortlist){
            longlist = longlist.next;
            shortlist = shortlist.next;
        }
        return shortlist;
    }

    private int getListLength(ListNode pHead){
        int length = 0;
        ListNode cur = pHead;
        while(cur != null){
            length++;
            cur = cur.next;
        }
        return length;
    }
}

解题关键

找到长短链表的差距,让长链表走完这个距离

全部评论

相关推荐

不愿透露姓名的神秘牛友
07-23 14:13
这是聊岔撇了吗,相同的话问了两遍
吴offer选手:上下文切换这一块
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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