牛客题霸NC04题解

判断链表中是否有环

https://www.nowcoder.com/practice/650474f313294468a4ded3ce0f7898b9?tpId=117&&tqId=34925&rp=1&ru=/ta/job-code-high&qru=/ta/job-code-high/question-ranking

判断链表中是否有环

牛客题霸NC93

难度:Easy

题目描述

判断给定的链表中是否有环,你能给出空间复杂度img的解法么?

题目解答

1. Set+遍历

遍历链表,将遍历的每个节点放到一个Set里。如果遍历过程中发现Set中已经存在该节点,则代表链表存在环;如果遍历到末尾,则代表链表无环。

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) {

        Set<ListNode> set = new HashSet<>();
        while(head != null){
            if(set.contains(head)){
                return true;
            }
            set.add(head);
            head = head.next;
        }

        return false;
    }
}

时间复杂度:O(n)

空间复杂度:O(n)

2. 快慢指针相遇

设置快慢两个指针,如果两个指针最终相遇,代表链表存在环;若快指针到达链表末尾,则代表不存在环。

/**
 * 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 || head.next == null){
            return false;
        }

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

        return false;
    }
}

时间复杂度:O(n)

空间复杂度:O(1)

全部评论

相关推荐

点赞 评论 收藏
分享
评论
2
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务