思路:
方法1.可以使用hashset,重复返回true
方法2:使用两个指针,fast和slow,两个指针重合时
public class Solution {
public boolean hasCycle(ListNode head) {
if (head == null)
return false;
HashSet<ListNode> set = new HashSet<ListNode>();
while(head!=null) {
if(set.contains(head)) {
return true;
}
set.add(head);
head = head.next;
}
return false;
}
}
public class Solution {
public boolean hasCycle(ListNode head) {
if (head == null)
return false;
ListNode fast = head,
slow = head;
while(true) {
if(fast.next != null && fast.next.next!=null) {
fast = fast.next.next;
slow = slow.next;
}else{
return false;
}
if(slow == fast) {
return true;
}
}
}
}
本文介绍两种检测链表中是否存在循环的有效方法:一是利用HashSet记录遍历过的节点;二是采用快慢指针技巧,通过比较两者是否相遇来判断循环的存在。
1760

被折叠的 条评论
为什么被折叠?



