解法一:快慢指针,当快指针追上慢指针说明链表是环形的
时间复杂度O(N) 空间复杂度O(1)
java描述:
public boolean hasCycle(ListNode head) {
ListNode walker = head;
ListNode runner = head;
while (runner != null && runner.next != null) {
walker = walker.next;
runner = runner.next.next;
if (walker == runner) {
return true;
}
}
return false;
}
javaScript描述:
var hasCycle = function(head) {
let slow = head;
let falst = head;
while(falst != null && falst.next != null) {
falst = falst.next.next;
slow = slow.next;
if (falst === slow) return true;
}
return false;
};
解法二:暴力解法,利用哈希表
时间复杂度O(N) 空间复杂度O(N)
public boolean hasCycle(ListNode head) {
Set<ListNode> node = new HashSet<ListNode>();
while (head != null) {
if (node.contains(head)) {
return true;
}else {
node.add(head);
}
head = head.next;
}
return false;
}
javaScript描述:
var hasCycle = function(head) {
let nodes = new Set();
while (head) {
if (nodes.has(head)) return true;
nodes.add(head);
head = head.next;
}
return false;
};
注意:数据结构 Set。它类似于数组,但是成员的值都是唯一的,没有重复的值。