剑指offer 23.链表中环的入口结点

题目描述

给定一个链表,若其中包含环,则输出环的入口节点。
若其中不包含环,则输出null。
在这里插入图片描述

解题思路

1、准备快慢两个指针,同时从链表的头指针开始走,慢指针走一步,快指针走两步,当这个两个指针相遇时,则链表存在环。
2、这时快指针回到链表的头指针,快指针和慢指针这次每次都走一步,当这两个指针再次相遇时,则为链表中环的入口结点

代码
/**
 * Definition for singly-linked list.
 * class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
class Solution {
    public ListNode entryNodeOfLoop(ListNode head) {
        if(head == null || head.next == null || head.next.next == null){
            return null;
        } 
        ListNode slow = head.next;
        ListNode fast = head.next.next;
        
        while(slow != fast){
            if(fast.next == null || fast.next.next == null){
                return null;
            }
            fast = fast.next.next;
            slow = slow.next;
        }        
        fast = head;
        while(slow != fast){
            slow = slow.next;
            fast = fast.next;
        }
        return slow;
        
    }
}

猜你喜欢

转载自blog.csdn.net/LiuXiaoXueer/article/details/107806853