Merging two sorted linked lists

前端 未结 14 2206
半阙折子戏
半阙折子戏 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 01:09

    The most glaring bug is in your loop, you keep overwriting mergedList->next, losing the previously added node. That is, your returned list will never contain more than two nodes, regardless of input ...

    It's been a while since I did C, but I would do it as follows:

    Node* merge(Node* list1, Node* list2) {
        Node* merged = null;
        Node** tail = &merged;
    
        while (list1 && list2) {
            if (list1->data < list2->data) {
                *tail = list1;
                list1 = list1->next;
            } else {
                *tail = list2;
                list2 = list2->next;
            }
            tail = &((*tail)->next);
        }
        *tail = list1 ? list1 : list2;
        return merged;
    }
    

提交回复
热议问题