141. Linked List Cycle

一、题目

  1、审题

    

  2、分析

    给出一个链表,查看其中是否存在一个环。

二、解答

  1、思路:

    方法一、

      使用一个 Set 存储遍历的节点,当当前遍历的节点不存在于 Set 中,则加入 Set,若已存在于 Set,则返回 true。

    public boolean hasCycle(ListNode head) {
        
        ListNode tmpNode = head;
        Set<ListNode> set = new HashSet<ListNode>();
        while(tmpNode != null) {
            if(set.contains(tmpNode))
                return true;
            set.add(tmpNode);
            tmpNode = tmpNode.next;
        }
        return false;
    }

  

  方法二、

    设置两个指针,walker 每次向后移动一个单位,runner 每次向后移动两个单位。

    若 List 中存在一个环,则最终 walker 与 runner 会有相遇。

    public boolean hasCycle(ListNode head) {
        if(head == null)
            return false;
        
        ListNode walker = head;
        ListNode runner = head;
        while(runner.next != null && runner.next.next != null) {
            walker = walker.next;
            runner = runner.next.next;
            if(walker == runner)
                return true;
        }
        return false;
    }
原文地址:https://www.cnblogs.com/skillking/p/9775308.html