题目:环形链表判断
判断一个链表中是否存在环形链表
解题思路:利用快慢指针思想
快指针每次走两个结点,慢指针每次走一个结点,当快指针和慢指针相遇的时候就说明存在环形链表,若当快指针走到null且快指针的next走到null的时候,还未相遇,那么链表中不存在环形链表。
代码实现:
public class ListNode(){
ListNode next;
int val;
ListNode(int x){
val = x;
}
}
public boolean hasCycle(ListNode head){
if(head == null || head.next == null)return false;
ListNode slow = head;
ListNode fast = head.next;
while(fast != null && fast.next != null){
slow = slow.next;
fast = fast.next.next;
if(slow == fast)return true;
}
return false;
}
复杂度分析
按结点的规模可知,复杂度为O(n)