leetcode
第141题:环形列表
第一种:哈希列表
public boolean hasCycle(ListNode head) {
Set<ListNode> seen = new HashSet<ListNode>();
while (head != null) {
if (seen.contains(head)) {
return true;
}
seen.add(head);
head = head.next;
}
return false;
}
第二种:快慢指针:
快指针走两步,慢指针走一步,相遇则说明有环
if (head == null || head.next == null) {
return false;
}
ListNode slow = head;
ListNode fast = head.next;
while (slow != fast) {
if (fast == null || fast.next == null) {
return false;
}
slow = slow.next;
fast = fast.next.next;
}
return true;
}
标签:head,null,return,141,fast,next,slow,列表,leetcode
From: https://www.cnblogs.com/ldy20020324/p/18008259