1、链接: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?
2、思路:设置快慢指针,如果有cycle则会相遇,没有的话,快指针最终会走到tail
3、代码:
public class Solution {
boolean isCycle = false;
public boolean hasCycle(ListNode head) {
ListNode first = head;
ListNode second = head;
while(second != null){
first = first.next;
if(second.next == null)
break;
second = second.next;
second = second.next;
if(first == second){
isCycle = true;
break;
}
}
return isCycle;
}
}