题目描述
Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
public class Solution {
/**
* 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?
* 利用快慢指针,一个走的快,一个走的慢,如果存在环,快的肯定会追到慢的
*
* */
public boolean hasCycle(ListNode head) {
if (head==null||head.next==null) {
return false;
}
ListNode low = head, fast = head;
while(fast!=null&&fast.next!=null) {
fast = fast.next.next;
low = low.next;
if (fast==low) {
return true;
}
}
return false;
}
}