c# using dictionary story addresses of list nodes O(n) solution but needs extra space


  • 0
    N
    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     public int val;
     *     public ListNode next;
     *     public ListNode(int x) {
     *         val = x;
     *         next = null;
     *     }
     * }
     */
    public class Solution {
        public ListNode DetectCycle(ListNode head) {
            
            var current = head;
            var fakeHead = new ListNode(-1);
            fakeHead.next = head;
            
            if(head == null || head.next == null)
            {
                return null;
            }
            
            var dict = new System.Collections.Generic.Dictionary<ListNode, int>();
            dict.Add(fakeHead.next, -1);
            
            while(current.next!= null && current != null)
            {
                try
                {                
                    dict.Add(current.next, current.val);   
                    current = current.next;
                    
                }
                catch(ArgumentException ex)
                {
                    return current.next; 
                }
            }
            return null;
        }
    }
    

Log in to reply
 

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