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;
}
}
本文介绍了一种使用快慢指针的方法来判断链表中是否存在环。通过一个快速指针每次移动两步和一个慢速指针每次移动一步,如果两者相遇则说明链表中有环存在。
5702

被折叠的 条评论
为什么被折叠?



