题目内容
Given a linked list, determine if it has a cycle in it.
题目分析
判断一个链表是否有环, 设置fast和slow两个flag,当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) {
ListNode fast=head;
ListNode slow=head;
while(fast!=null&&fast.next!=null)
{
fast=fast.next.next;
slow=slow.next;
if (slow==fast) {
return true;
}
}
return false;
}
}