A simple and fast solution, different from others.


  • 0
    D
     public class Solution {
        public boolean hasCycle(ListNode head) {
            if (head == null)
                return false;
            ListNode node = head.next;
            ListNode node1 = head.next;
            while (node != null) {
                if (node.next == head)
                    return true;
                node = node.next;
                node1.next = head;
                node1 = node;
            }
            return false;
        }
    }
    
    1. Traverse the LinkedList, set the node point to the head node.
    2. If the Linked List has a cycle, there will be a node point to the head node.

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.