判断是否为环形链表

给定一个链表,判断链表中是否有环。
若是链表中有某个节点,能够经过连续跟踪 next 指针再次到达,则链表中存在环。 为了表示给定链表中的环,咱们使用整数 pos 来表示链表尾链接到链表中的位置(索引从 0 开始)。 若是 pos 是 -1,则在该链表中没有环。注意:pos 不做为参数进行传递,仅仅是为了标识链表的实际状况。
若是链表中存在环,则返回 true 。 不然,返回 falsejava

package com.loo;node

import java.util.Set;
import java.util.LinkedHashSet;oop

public class LoopPointer {
    public static void main(String[] args) {
        ListNode head = new ListNode(0);
        ListNode l1 = new ListNode(1);
        ListNode l2 = new ListNode(2);
        ListNode l3 = new ListNode(3);
        ListNode l4 = new ListNode(4);
        ListNode l5 = new ListNode(5);
        ListNode l6 = new ListNode(6);
        head.next = l1;
        l1.next = l2;
        l2.next = l3;
        l3.next = l4;
        l4.next = l5;
        l5.next = l6;
        l6.next = l2;
        System.out.println(hasLoopPointer(head)); // hash表
        System.out.println(slowAndFastLoopPointer(head));  // 快慢指针
    }指针

    static class ListNode {
        int value;
        ListNode next;
        public ListNode(int v) {
            value = v;
        }
    }索引

    public static boolean hasLoopPointer(ListNode node) {
        Set<ListNode> set = new LinkedHashSet<ListNode>();
        while (node!=null) {
            if (set.contains(node)) {
                return true;
            }
            set.add(node);
            node = node.next;
        }
        return false;
    }hash

    public static boolean slowAndFastLoopPointer(ListNode node) {
        if (node==null) {
            return false;
        }
        ListNode s = node;
        ListNode f = node.next;
        while (f!=null && f.next!=null) {
            if (s.equals(f)) {
                return true;
            }
            s = s.next;
            f = f.next.next;
        }
        return false;
    }
}ast