【数据结构】算法 Linked List Cycle 环形链表是否有环

Linked List Cycle 环形链表

哈希表

利用哈希特性,在遍历的同时将节点插入hash;如果插入失败代表链表有环。

/**
 * 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;
        }
        HashSet<ListNode> set = new HashSet<ListNode>();    
        ListNode p = head;
        while(p.next!=null){
            if(!set.add(p)){
                return true;        
            }
            p =p.next;
        }
        return false;
    }
}

双指针

使用双指针fast,slow,fast一次移动2个node,slow一次移动1个node

  • 在存在环的链表中 fastslow一定会在环中相遇。
  • 如果没有环,fast一定会最先抵达表尾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) {
        if(head==null){
            return false;
        }
        ListNode p = head; 
        ListNode q = head.next;
        while(p!=q&&q!=null&&q.next!=null){
            p = p.next;
            q = q.next.next;
        }
        return q!=null&&q.next!=null;
    }
}
原文地址:https://www.cnblogs.com/dreamtaker/p/14505682.html