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) {
if(head==null){
return false;
}else if(head.next==head){
return true;
}else if(head.next==null){
return false;
}
ListNode quick=head;
ListNode slow=head;
boolean isFirst=true;
while(quick!=null){
if(quick==slow&&!isFirst){
return true;
}
quick=quick.next;
if(quick==null){
return false;
}
slow=slow.next;
quick=quick.next;
isFirst=false;
}
return false;
}
}