Linked List Cycle II {3,2,0,-4}, tail connects to node index 1


  • 1
    H

    this is my code

    public class Solution {
        public ListNode detectCycle(ListNode head) {
            if(head == null || head.next == null){
                return null;
            }
            ListNode res = null;
            ListNode stepOne = head;
            ListNode stepTwo = head;
            while(res == null){
                stepOne = stepOne.next;
                stepTwo = stepTwo.next.next;
                if(stepTwo == null || stepTwo.next == null){
                    break;
                }else if(stepOne == null || stepOne.next == null){
                    break;
                }else if(stepOne == stepTwo){
                    ListNode node = head;
                    while(node != stepOne){
                        node = node.next;
                    }
                    res = node;
                }
            }
            return res;
        }
    }
    

    Input: {3,2,0,-4}, tail connects to node index 1
    Output: tail connects to node index 3
    Expected: tail connects to node index 1


  • 0
    L

    Hi, I have the same problem. Would you mind describing how did you solve it?


Log in to reply
 

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