Wrong answer, input {3, 4, 1}, output {1, 3}


  • 0
    J

    Can anyone help me with the following code?

    class Solution {
    public:
        ListNode *insertionSortList(ListNode *head) {
                  if(head == NULL) return head;
            ListNode* new_head = new ListNode(INT_MIN);
            new_head->next = head;
            ListNode* pointer = head;
            while(pointer)
            {
                ListNode* comp = new_head;
                ListNode* comp_prev = NULL;
                while(comp != pointer)
                {
                    if(comp->val > pointer->val)
                    {
                        if(comp_prev)
                        {
                            comp_prev->next = pointer;
                        }
                        ListNode* temp = pointer->next;
                        pointer->next = comp;
                        comp->next = temp;
    
                        break;
                    }
                    comp_prev = comp;
                    comp = comp->next;
                }
                pointer = pointer->next;
            }
            ListNode* result = new_head->next;
            delete new_head;
            return result;
        }
    };
    

    I tested it on my laptop, and the output is {1, 3,4}, but the online judge system only outputs {1, 3}. Also, I think I have a memory error, but not sure where it is.


  • 0
    T

    Are you sure you were testing on [3,4,1] on your laptop? The only difference can be the input to the method. Try printing the hole list inside insertionSortList and see if there's a difference.


Log in to reply
 

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