141. Linked List Cycle
Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
思路1:naive思路用Hashset,看看重复了没有。但是需要extra space
public boolean hasCycle(ListNode head) {
if (head==null){
return false;
}
HashSet<ListNode> set = new HashSet<ListNode>();
while(head.next!=null){
head = head.next;
if (set.contains(head)){
return true;
}else{
set.add(head);
}
}
return false;
}
}
思路2:用双指针,一快一慢。想像他们是在一个操场跑步,如果有圈总会遇上
public class Solution {
public boolean hasCycle(ListNode head) {
if (head==null){
return false;
}
ListNode walk = head;
ListNode run = head;
while(run.next!=null&&run.next.next!=null){
walk = walk.next;
run = run.next.next;
if (walk==run){
return true;
}
}
return false;
}
}