判断一个单链表是否循环.
解题思想,龟兔赛跑原理,如果有循环的话,乌龟和兔子总会相遇(小学数学书中的龟兔相遇问题)。
Java version
/**
* 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;
ListNode oneStep = head;
ListNode twoStep = head;
while(oneStep !=null && twoStep !=null && twoStep.next != null){
oneStep = oneStep.next;
twoStep = twoStep.next.next;
if(oneStep == twoStep) return true;
}
return false;
}
}