Java Solution by Reverse the LinkedList (and reconstruct back)


  • 0
    public boolean hasCycle(ListNode head) {
        if(head==null || head.next==null)
            return false;
        if(head.next==head || head.next.next==head)
            return true;
        ListNode newHead = null;
        ListNode node = head;
        boolean res = false;
        while(node!=null) {
            ListNode nextNode = node.next;
            node.next = newHead;
            newHead = node;
            node = nextNode;
            if(node==head) {
               node.next = newHead;
               newHead = node;
               res = true;
               break;
            }
        }
        /*
        // reconstruct the original list
        head = null;
        node = newHead;
        while(node!=null) {
            ListNode nextNode = node.next;
            node.next = head;
            head = node;
            node = nextNode;
            if(node==head) {
                node.next = head;
                head = node;
                break;
            }
        }
        */
        return res;
    }

Log in to reply
 

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