判断链表中是否有环

牛客题霸NC93

难度:Easy

题目描述

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

题目解答

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)

相关文章:

  • 2021-10-24
  • 2022-01-01
  • 2021-04-07
  • 2022-01-12
  • 2021-12-17
  • 2022-12-23
  • 2021-06-10
  • 2021-04-11
猜你喜欢
  • 2022-01-16
  • 2021-07-27
  • 2021-10-31
  • 2021-08-23
  • 2021-09-05
  • 2021-10-06
  • 2022-01-06
相关资源
相似解决方案