LeetCode141 - 环形链表(简单)
链接:https://leetcode-cn.com/problems/linked-list-cycle/
给定一个链表,判断链表中是否有环
解法一、时间复杂度O(n),空间复杂度O(n)
/**
* 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;
// set里存的一定是node节点,不能是val,因为引用类型 == 和 != 是比较的内存地址
Set<ListNode> set = new HashSet<>();
// 有环在循环内会结束,无环肯定会跳出来
while(head != null) {
if(!set.add(head)) {
return true;
}
head = head.next;
}
return false;
}
}
解法二、快慢指针,时间复杂度O(n),空间复杂度O(1)
/**
* 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 fast = head.next;
ListNode slow = head;
// 利用快慢指针,有环肯定会相遇,无环快指针肯定先跳出
while(fast != slow) {
slow = slow.next;
if(fast == null || fast.next == null) {
return false;
}
fast = fast.next.next;
}
return true;
}
}
解法二的第二种写法(推荐):
/**
* 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 fast = head;
ListNode slow = head;
while(fast != null && fast.next != null) {
fast = fast.next.next;
slow = slow.next;
if(slow == fast) {
return true;
}
}
return false;
}
}