-
2.10
- 秒了
-
1.19
- 第二遍做出来很轻松了,虽然还是判错了条件
- 第二遍没有用 set 那个
public class Solution {
public boolean hasCycle(ListNode head) {
if(head==null||head.next==null) return false;
ListNode slow = head;
ListNode fast = head;
while(fast!=null&&fast.next!=null){
slow = slow.next;
fast = fast.next.next;
if(slow==fast) return true;
}
return false;
}
}- 11.9
- 需要对head和head.next作判空判断
public class Solution {
public boolean hasCycle(ListNode head) {
Set<ListNode> set = new HashSet<ListNode>();
while(head!=null){
if(!set.add(head)){
return true;
}
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;
}- 解法1
- 创建set集合,靠添加进是否成功来判断环形链表
- 解法2
- 快慢指针,快的走两步,以相遇或到终点为终止条件