问题如下:
Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
思路:利用快慢指针,快的在某一时刻追上慢的指针说明有环
package leetcode9.LinkHasOrNotCycle;
class ListNode{
int val;
ListNode next;
ListNode(int x){
val=x;
next=null;
}
}
public class Solution {
public boolean hasCycle(ListNode head){
if (head==null){
return false;
}
ListNode fast=head;
ListNode slow=head;
while(fast.next!=null){
fast=fast.next.next;
if(fast.next==null){
return false;
}
slow=slow.next;
if(fast==slow)
return true;
}
return false;
}
}
总结:又一次利用快慢指针,这个思想在处理链表时要考虑到(上文是判断中间节点)