Merging two sorted linked lists

前端 未结 14 2181
半阙折子戏
半阙折子戏 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:49

    I have created recursion function for it. Here is my solution:

    Node* merge_recursion(Node* l1, Node* l2)
    {
            if (!l1)
                    return l2;
            if (!l2)
                    return l1;
    
            if (l1->data < l2->data) {
                    l1->next = merge_recursion(l1->next, l2);
                    return l1;
            } else {
                    l2->next = merge_recursion(l1, l2->next);
                    return l2;
            }
    }
    

    Store return pointer into new pointer variable (in main() / calling function) and traverse linked list on new pointer to print data, it will result sorted merged linked list.

提交回复
热议问题