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

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

https://www.nowcoder.com/practice/6ab1d9a29e88450685099d45c9e31e46?tpId=188&&tqId=38581&rp=1&ru=/activity/oj&qru=/ta/job-code-high-week/question-ranking

二刷

/*
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 len1 = 0;
        for(ListNode cur = pHead1; cur!=null;cur = cur.next) len1++;
        int len2 = 0;
        for(ListNode cur = pHead2; cur!=null;cur = cur.next) len2++;
        ListNode c1 = pHead1;
        ListNode c2 = pHead2;
        if(len1 > len2){
            for(int i = len1-len2;i>0;i--){c1 = c1.next;}
        }
        else{
             for(int i = len2-len1;i>0;i--){c2 = c2.next;}
        }

        while(c1!=c2){
            c1 = c1.next;
            c2 = c2.next;
        }
        return c1;
    }
}

1.没啥好说的 对其尾部, 从短的那个开始向后判断

/*
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 smalllength;
        int length1 = 0;
        int length2 = 0;
        ListNode cur1;
        ListNode cur2;
        for(cur1 = pHead1;cur1!=null;cur1 = cur1.next){
            length1++;
        }
        for(cur2 = pHead2;cur2!=null;cur2 = cur2.next){
            length2++;
        }
        cur1 = pHead1;
        cur2 = pHead2;
        smalllength = length1 < length2 ? length1 : length2;
        if(smalllength == length1){
            for(int i = length2-smalllength; i>0; i--){
                cur2 = cur2.next;
            }
        }
         else{
             for(int i = length1-smalllength; i>0; i--){
                cur1 = cur1.next;
            }
        }

        while(cur1!=null && cur2!=null){
            if(cur1 == cur2){
                return cur1;
            }
            cur1 = cur1.next;
            cur2 = cur2.next;
        }
        return null;
    }
}
面试题解 文章被收录于专栏

面试题解

全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务