Runtime Error for a C# solution


  • 0
    P

    Happens for the test case with many long lists. Is this hitting a stack overflow on the server side?

    Here is the code, Don't see anything wrong with it.

    public class Solution {
        public ListNode MergeKLists(ListNode[] lists) {
            if(lists.Length == 0)
                return null;
            
            List<ListNode> list = new List<ListNode>(lists);
            
            while(list.Count > 1)
            {
                ListNode temp = MergeLists(list[0], list[1]);
                list.Add(temp);
                
                // Remove the lists that we just merged.
                list.RemoveAt(0);
                list.RemoveAt(0);
            }
            
            return list[0];
        }
        
        private ListNode MergeLists(ListNode x, ListNode y)
        {
            ListNode result;
            
            if(x == null)
                return y;
            if(y == null)
                return x;
            if(x.val <= y.val)
            {
                x.next = MergeLists(x.next, y);
                return x;
            }
            else
            {
                y.next = MergeLists(x, y.next);
                return y;
            }
        }
    }
    

    Thanks.


Log in to reply
 

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