给定一个链表,判断链表中是否有环。
进阶:
你能否不使用额外空间解决此题?
解答:
使用两个指针遍历链表,一个快指针(一次走两个),一个慢指针(一次走一个)。如果两个指针相遇,则链表中含有环形。如果快指针到达结尾,则链表中没有环路。
时间复杂度:O(n)O(n)O(n)
空间复杂度:O(1)O(1)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 != null){
fast = fast.next;
if (fast == null) return false;
fast = fast.next;
slow = slow.next;
if (fast == slow) return true;
}
return false;
}
}
使用HashSet记录遍历过的节点,如果有重复节点,则返回存在环路。
时间复杂度:O(n)O(n)O(n)
空间复杂度:O(n)O(n)O(n)
public static 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;
}