Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
这个问题也比较简单,我就直接贴出解题部分的代码了~
问题的核心在于设一个快指针和一个慢指针,如果“有一天”慢的追上了快的,说明中间一定有环儿~
Public class LLCycle {
/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
class ListNode{
int val;
ListNode next;
ListNode(int x){
val = x;
next=null;
}
}
<span style="white-space:pre"> </span>//以下为解题部分
public boolean hasCycle(ListNode head) {
if(head==null||head.next==null) return true;
ListNode slow=head;
ListNode fast=head;
while(true){
if(fast==null||fast.next==null) return true;
slow=slow.next;
fast=fast.next.next;
if(fast==slow) return false;
}
}
}