题意:判断一个单链表是否存在环
分析:
设置两个指针(fast, slow),初始值都指向头,slow每次前进一步,fast每次前进二步,如果链表存在环,则fast必定先进入环,而slow后进入环,两个指针必定相遇 。
时间复杂度:O(n)
代码:
/**
* 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 || head.next == null) return false;
ListNode fastNode = head.next;
ListNode slowNode = head;
while(fastNode != null && fastNode.next != null){
if(fastNode == slowNode){
return true;
}
fastNode = fastNode.next.next;
slowNode = slowNode.next;
}
return false;
}
}