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

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

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;
        }
        ListNode p1 = pHead1;
        ListNode p2 = pHead2;
        int flag1 = 0;
        int flag2 = 0;
        while (p1 != null) {
            flag1++;
            p1 = p1.next;
        }
        while (p2 != null) {
            flag2++;
            p2 = p2.next;
        }
        if (flag1 > flag2) {
            flag1 = flag1 - flag2;
            for (int i = 0; i < flag1 ; i++) {
                pHead1 = pHead1.next;
            }
        } else {
            flag1 = flag2 - flag1;
            for (int i = 0; i < flag1 ; i++) {
                pHead2 = pHead2.next;
            }
        }
        while (pHead1 != null && pHead2 != null) {
            if (pHead1.val == pHead2.val) {
                return pHead1;
            }
            pHead1 = pHead1.next;
            pHead2 = pHead2.next;
        }

        return null;
    }
}

1.设置 p1 p2 用于指向两链表以及 flag1 flag2 用于计数,遍历两个链表得到表长存入 flag1 flag2

2.将两个链表表长相减,假设 链表1 长度大于 链表2 ,那么将链表1 向前移动链表2 个长度,这样操作使得两个链表后续长度相同,处于同一起跑线

3.从新位置对两个链表向后遍历,直到两表值相等为止,每次遍历指针向后移动一位

全部评论

相关推荐

05-30 12:03
山西大学 C++
offer来了我跪着...:不是骗子,等到测评那一步就知道为啥这么高工资了
点赞 评论 收藏
分享
06-28 22:48
已编辑
广东金融学院 Java
小浪_Coding:学院本+这俩项目不是buff叠满了嘛
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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