0
点赞
收藏
分享

微信扫一扫

leetcode 给定一个链表,返回链表开始入环的第一个节点。 如果链表无环,则返回 null。

i奇异 2022-01-06 阅读 45

给定一个链表,返回链表开始入环的第一个节点。 如果链表无环,则返回 null。

/**
 * 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 || head.next==null || head.next.next==null)//排除特殊情况
            return null;
        ListNode fast = head.next.next;
        ListNode slow = head.next;
        while(fast!=slow && fast!=null && fast.next!=null) { 
            fast = fast.next.next;
            slow = slow.next;
        }
        if(fast!=slow)
            return null;
        fast = head;
        while(fast!=slow) {
            fast = fast.next;
            slow = slow.next;
        }
        return fast;
    }
}
举报

相关推荐

0 条评论