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

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

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 ph1 = pHead1;
        ListNode ph2 = pHead2;
        int l1 = 0;
        int l2 = 0;
        while(ph1 != null){
            ph1 = ph1.next;
            l1++;
        }
        while(ph2 != null){
            ph2 = ph2.next;
            l2++;
        }
        if(l1 == l2){
            while(pHead1 != pHead2){
                pHead1 = pHead1.next;
                pHead2 = pHead2.next;
            }
            return pHead1;
        }
        else if(l1>l2){
            int l= l1-l2;
            while(l-->0){
                pHead1 = pHead1.next;
            }
            while(pHead1 != pHead2){
                pHead1 = pHead1.next;
                pHead2 = pHead2.next;
            }
            return pHead1;
        }
        else{
            int l= l2-l1;
            while(l-->0){
                pHead2 = pHead2.next;
            }
            while(pHead1 != pHead2){
                pHead1 = pHead1.next;
                pHead2 = pHead2.next;
            }
            return pHead1;
        }
    }
}

常规思路求解,得出长度差然后先走长度差个节点 之后就一起走

全部评论

相关推荐

想进开水团喝开水:哦 给我一个 就算你真拿到牛友也会为你开心的
点赞 评论 收藏
分享
迷茫的大四🐶:价格这么低都能满了?
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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