Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
分析
这题用hashset很容易
如果不用set,可以用slow,fast双指针,fast走的快,如果有环的话,迟早会在后面的几圈会赶上slow。
/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public boolean hasCycle(ListNode head) {
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;
}
fast = fast.next.next;
slow = slow.next;
}
return true;
}
}