Simple C++ Code, fast and easy to undersatnd


  • 0
    J

    class Solution {
    public:
    ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {

        ListNode* head = new ListNode(0);
        ListNode* it = head;
        
        while(l1 && l2)
        {
            if( l1->val < l2->val) 
            {
                it->next = l1;
                it = l1;
                l1 = l1->next;
            }
            else
            {
                it->next = l2;
                it = l2;
                l2 = l2->next;
            }
        }
        
        if(l1)   it->next = l1;
        if(l2)   it->next = l2;
        
        it = head->next;
        delete head;
        head = NULL;
    
        
        return it;
    }
    

    };


  • 0

    should be "return it"...
    I'm surprised your code even passed when you tried to return head after deleting it


  • 0
    J

    @davidyuan7536
    Thanks for reminder! It should be "return it".
    When you use "delete p" to delete a certain pointer, a message is sent that the memory occupied by the pointer can currently be used to store other data. But the program may not do that immediately, "head -> next" possibly still works. I should add a line "head = NULL;" after the delete command.


Log in to reply
 

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