Merging two sorted linked lists

前端 未结 14 2180
半阙折子戏
半阙折子戏 2020-12-01 00:12

This is one of the programming questions asked during written test from Microsoft. I am giving the question and the answer that I came up with. Thing is my answer although l

14条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-01 00:51

    This is my take. Unlike other solutions it identifies and skips over consecutive nodes on one list which are smaller or equal to the head node of the other list. The head of the other list is attached at the end of such sequence and the process is repeated after switching roles. This approach minimizes the number of assignments to Node.next while limiting NULL testing to single check in each iteration.

    Node * merge(Node *list1, Node *list2)
    {
        if (!list1) return list2;
        if (!list2) return list1;
    
        Node *tmp;
    
        // compare head nodes and swap lists to guarantee list1 has the smallest node
        if (list1->val > list2->val) {
            tmp = list2;
            list2 = list1;
            list1 = tmp;
        }
    
        Node *tail = list1;
    
        do {
            // Advance the tail pointer skipping over all the elements in the result
            // which have smaller or equal value than the first node on list2
            while (tail->next && (tail->next->val <= list2->val)) {
                tail = tail->next;
            }
            // concat list2 at tail of result and make the rest after tail list2 
            tmp = tail->next;
            tail->next = list2;
            tail = list2;
            list2 = tmp;
        } while (list2);
    
        return list1;
    }
    

提交回复
热议问题