剑指offer -- 判断链表中是否有环
判断链表中是否有环
http://www.nowcoder.com/questionTerminal/650474f313294468a4ded3ce0f7898b9
解法
快慢指针的解法, 一个指针走两步 一个指针走一步,如果快指针直接到了null 说明没有环, 如果有环的话 总有一次结果会让快指针和慢指针相等。
代码
/**
* 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) {
ListNode p = head;
ListNode q = head;
while(p!=null && p.next!=null){
p = p.next.next;
q = q.next;
if(p==q){
return true;
}
}
return false;
}
} 