链接:https://leetcode.com/problems/linked-list-cycle/
原题:
Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
分析:这道题的意思是在不开辟另外内存空间的情况下 判断是否是循环的链表
这里用两个游标用来做比较,一个是一个跳两个节点,一个是一次跳一个节点,如果是循环链表,两个游标肯定有重合的时候
/**
* 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 (true) {
if(fast == null || slow== null) {
return false;
}
fast = fast.next;
if(slow.next!=null) {
slow = slow.next.next;
} else {
return false;
}
if(fast == slow) {
return true;
}
}
}
}