题目
Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
思路
通过快慢指针来做.如果存在环,那么通过快慢指针,一定可以让快指针指向满指针(并且快指针指向的当前位置和下一个位置都不是null
但是如果不存在环,那么就快指针就可能指向null
代码
/**
* 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) {
boolean result = false;
if( head == null)
{
return result;
}
ListNode quick = head;
ListNode slow = head;
while(quick!=null &&quick.next != null)
{
quick = quick.next;
quick = quick.next;
slow = slow.next;
if(quick == slow)
{
return true;
}
}
return result;
}
}