20200406——第一百四十二题 环形链表二

/**
 * Definition for singly-linked list.
 * class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public ListNode detectCycle(ListNode head) {
        if(head == null){
            return null;
        }
        ListNode get = getCore(head);
        if(get == null){
            return null;
        }
        ListNode set = head;
        while(set != get){
            set = set.next;
            get = get.next;
        }
        return set;
    }

    public ListNode getCore(ListNode head){
        if(head == null){
            return null;
        }
        ListNode fast = head;
        ListNode slow = head;

        while(fast != null && fast.next !=null){
            slow = slow .next;
            fast = fast.next.next;
            if(slow == fast){
                return slow;
            }
        }
        return null;
    }
}

在这里插入图片描述

发布了955 篇原创文章 · 获赞 43 · 访问量 8万+

猜你喜欢

转载自blog.csdn.net/qq_36344771/article/details/105349186