题解 | #判断链表中是否有环#
判断链表中是否有环
http://www.nowcoder.com/practice/650474f313294468a4ded3ce0f7898b9
双指针(快慢双指针)
public class Solution {
public boolean hasCycle(ListNode head) {
if(head == null)return false;
ListNode t1 = head;//慢指针
ListNode t2 = head;//快指针
while(t2 != null && t2.next != null){
t1 = t1.next;
t2 = t2.next.next;
if(t1 == t2)return true;
}
return false;
}
}
暴力
观察数据,发现节点最多10000个,直接循环计数,循环的次数大于10000即代表出现了环
public class Solution {
public boolean hasCycle(ListNode head) {
//记录循环的次数
int ret = 0;
while(head != null){
ret++;
head = head.next;
if(ret > 11000){
break;
}
}
return ret > 11000;
}
}