Shall I take special action for the loop of two noes?


  • 0
    S

    Hi All,

    Should I take specail code for the loop of only two codes, as my solution will print the second node as result which is wrong?

    public ListNode detectCycle(ListNode head) {
    	if (head != null && head.next != null) {
    		if (head.next.next == head) {
    			return head;
    		}
    	}
    	ListNode slow = head;
    	ListNode fast = head;
    
    	ListNode firstNode = null;
    	if (head != null) {
    		slow = head;
    		fast = head;
    
    		while (slow.next != null && fast != null) {
    			slow = slow.next;
    			if (fast.next != null && fast.next.next != null) {
    				fast = fast.next.next;
    			} else {
    				break;
    			}
    			if (slow == fast) {
    				firstNode = slow;
    				slow = head;
    				break;
    			}
    		}
    	}
    
    	if (firstNode != null) {
    		while (true) {
    			slow = slow.next;
    			fast = fast.next;
    			if (slow == fast) {
    				return slow;
    			}
    		}
    	}
    	return null;
    }

  • 0
    G

    **

    i think if you devise a proper algorithm then the 2 node cycle case can be resolved.

    **


  • 0
    S

    Thank you. I post my solution, would you please take a look and give some comment?


Log in to reply
 

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