public SortedList quicksort(ListNode head) {
        // IMPORTANT: Please reset any member data you declared, as
        // the same Solution instance will be reused for each test case.
        
        if(head==null || head.next==null) return new SortedList(head, head);

        ListNode lHead = null;
        ListNode gHead = null;
        ListNode eHead = head;
        
        ListNode cur = head.next;
        head.next = null;
        ListNode temp;
        while(cur!=null) {
            if (cur.val > head.val) {
                temp = cur.next;
                
                // Insert current node before gHead node
                cur.next = gHead;
                gHead = cur;
                
                cur = temp;
                
            }
            else if(cur.val < head.val){
                temp = cur.next;
                
                cur.next = lHead;
                lHead = cur;
                
                cur = temp;
            }
            else {
                temp = cur.next;
                
                cur.next = eHead;
                eHead = cur;
                
                cur = temp;
            }
        }

        SortedList sl = quicksort(lHead);
        SortedList sg = quicksort(gHead);

        SortedList rs;
        if(sl.head==null && sg.head==null){
            rs = new SortedList(eHead, head);
        }
        else if(sl.head==null){
            head.next = sg.head;
            sg.tail.next = null;
            rs =  new SortedList(eHead, sg.tail);
        }
        
        else if (sg.head == null) {
            sl.tail.next = eHead;
            head.next = null;
            rs = new SortedList(sl.head, head);
        }
        
        else {
            sl.tail.next = eHead;
            head.next = sg.head;
            sg.tail.next = null;
            rs = new SortedList(sl.head, sg.tail);
        }
        return rs;
        
    }