给定一个链表,判断链表中是否有环。
/**
* 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;
boolean result = false;
while(fast != null) {
if(fast.next != null) {
fast = fast.next.next;
} else {
break;
}
slow = slow.next;
if(fast == slow) {
result = true;
break;
}
}
return result;
}
}
网友评论