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

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

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;
        }
    }
}

全部评论

相关推荐

做人要有梦想dji:最新工位查看图片
点赞 评论 收藏
分享
野猪不是猪🐗:把你的学校加黑,加粗,斜体,下划线,描边,内阴影,内发光,投影,外发光,再上渐变色,居中,放大到最大字号,再把简历里其它内容删了,就行了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务