Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
题解:
问题:判断链表是否有环。
分析:利用快慢指针slow,fast
slow指针每次走一步,fast指针每次走两步,倘若存在环,则slow和fast必定在某一时刻相遇。
由于fast指针走的比slow快所以循环的时候只需要判断fast和fast->next不为空,判断fast->next是因为防止出现fast->NULL->next这种情况
code:
/**
* 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)
{
return false;
}
ListNode slow,fast;
slow = head;
fast = head.next;
while(fast!=null && fast.next!=null)
{
if(slow==fast) return true;
slow = slow.next;
fast = fast.next.next;
}
return false;
}
}