两个链表的第一个公共结点_链表中环的入口结点

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

题目链接

//先计算长度差,然后让一个指针先走差值单位!
public class Solution {
    public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
            ListNode cur1 = pHead1;
            ListNode cur2 = pHead2;
        int size1 = 0;
        int size2 = 0;
        while(cur1!=null){
            cur1 = cur1.next;
            size1++;
        }
        while(cur2!=null){
            cur2 = cur2.next;
            size2++;
        }
        if(size1>size2){
            int len = size1 - size2;
            while(len-->0){
                pHead1 = pHead1.next;
            }
        }else{
             int len = size2 - size1;
            while(len-->0){
                pHead2 = pHead2.next;
            }
        }

        while(pHead1!=null){
            if(pHead1.val==pHead2.val){
                return pHead1;
            }
            pHead1 = pHead1.next;
            pHead2 = pHead2.next;
        }
        return null;
    }
}

36

  • 通过两个指针速度相同,走过的路程相同必会相遇!
  • cur1 走完 L1,cur1指向 L2,cur2走完L2,指向L1!
public class Solution {
    public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
            //定义2个指针! 
            // cur1 走完 L1,又从 L2开始!
            // cur2 走完 L2,又从 L1开始!
            // 这里两个指针速度相同,走过的长度相等,如果有相同节点肯定相遇!
        ListNode cur1 = pHead1;
        ListNode cur2 = pHead2;
        while(cur1!=cur2){//不存在公共节点,两个指针会来到null相等退出循环!
            cur1 = (cur1==null) ? pHead2 : cur1.next;
            cur2 = (cur2 == null) ? pHead1 : cur2.next;
        }
        return cur1;
    }
}

链表中环的入口结点

链表中环的入口结点

image-20220621092004731

image-20220621092032662

/*
 public class ListNode {
    int val;
    ListNode next = null;

    ListNode(int val) {
        this.val = val;
    }
}
*/
public class Solution {

    public ListNode EntryNodeOfLoop(ListNode pHead) {
        //快慢指针,利用链表头到入口距离 = 相遇点到入口距离!
        //所以当两个节点相遇后再走L距离就是入口位置!
        //相遇后让其中一个指针从链头开始走L,一个从相遇点开始!
        ListNode slow = pHead,fast = pHead;
        while(fast!=null&&fast.next!=null){//注意判断条件!!!!
            fast = fast.next.next;
            slow = slow.next;
            if(fast==slow){
                //相遇!
                //让slow从头结点开始!
                slow = pHead;
                while(fast!=slow){
                    slow = slow.next;
                    fast = fast.next;
                }
                return fast;
            }
        }
        return null;
    }
}
#笔试#
全部评论

相关推荐

08-08 16:33
唐山学院 Java
职场水母:首先,简历太长,对于实习和应届找工作,hr一眼扫的是学历,技术看实习,你写的技术栈字太多了,尽量用一句话概括不用写那么详细,技术面的时候会问的,而且技术栈都会在实习或者项目里体现,你要做的是,把你的简历浓缩为一页,删除没用的东西,比如实践经历,自我评价,这些纯废话,没用,专业技能写的太离谱,你真的熟练掌握了吗,建议都写熟悉,找工作和写论文不一样,追求的是干练和实用,把实习经历和项目提前,把掌握的技术栈写到最后,然后去找实习,
点赞 评论 收藏
分享
不愿透露姓名的神秘牛友
09-12 14:25
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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