题解 | #判断链表中是否有环#

判断链表中是否有环

https://www.nowcoder.com/practice/650474f313294468a4ded3ce0f7898b9

import java.util.*;
/**
 * Definition for singly-linked list.
 * class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public boolean hasCycle(ListNode head) {
        if (head == null) {
            return false;
        }
        // 双指针法,如果有循环,则必会相交
        ListNode targetNode = head;
        return hasCycle(head, targetNode);
    }

    public boolean hasCycle(ListNode head, ListNode targetNode) {
        if (targetNode.next == null || targetNode.next.next == null) {
            return false;
        }
        if (targetNode.next.next == head.next) {
            return true;
        }
        return hasCycle(head.next, targetNode.next.next);
    }
}

要求空间复杂度为O(1),可以使用双指针法,(slow指针每次移动一个位置,fast指针每次移动两个位置)如果存在闭环,那么最终必会相交。如果不存在闭环,那么最近获取next时会得到null值。

#闭环#
全部评论

相关推荐

不愿透露姓名的神秘牛友
07-07 18:05
点赞 评论 收藏
分享
点赞 评论 收藏
分享
Rena1ssanc...:对的,要是面评没太烂,勤更新简历等捞就行了,腾讯可以无限复活
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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