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

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

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) {
        // 输入两个无环的单向链表,找出它们的第一个公共结点,如果没有公共节点则返回空。
        //(注意因为传入数据是链表,所以错误测试数据的提示是用其他方式显示的,保证传入数据是正确的)
        int count1 = 0;
        int count2 = 0;
        ListNode head1 = pHead1;
        ListNode head2 = pHead2;
        while (head1 != null) {
            head1 = head1.next;
            count1++;
        }
        while (head2 != null) {
            head2 = head2.next;
            count2++;
        }

        head1 = pHead1;
        head2 = pHead2;
        int i = 0;
        for (i = 0; i < Math.abs(count1 - count2); i++) {
            if (count1 > count2) {
                head1 = head1.next;
            } else {
                head2 = head2.next;
            }
        }

        ListNode  res = null;
        boolean flag = true;

        while (head1 != null && head2 != null) {
            if (head1 == head2 && res == null) {
                res = head1;
            }
            if (res != null) {
                if (head1 != head2) {
                    flag = false;
                    break;
                }
            }
            head1 = head1.next;
            head2 = head2.next;
        }
        if (flag) {
            return res;
        } else {
            return null;
        }
    }
}

全部评论

相关推荐

程序员小白条:你是沟通了900个,不是投了900份简历,你能投900份,意味着对面都要回复你900次,你早就找到实习了,没亮点就是这样的,别局限地区,时间投的也要早,现在都要7月了
点赞 评论 收藏
分享
06-23 11:43
门头沟学院 Java
allin校招的烤冷...:我靠,今天中午我也是这个hr隔一个星期发消息给我。问的问题还是一模一样的😅
点赞 评论 收藏
分享
身边有人上海、深圳&nbsp;6、7k&nbsp;都去了,真就带薪上班了。
程序员小白条:木的办法, 以后越来越差,还是家附近宅着吧,毕业的人越来越多,岗位都提供不出来,经济又过了人口红利期
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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