Merging two sorted linked lists

前端 未结 14 2140
半阙折子戏
半阙折子戏 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;
    }
    
    0 讨论(0)
  • 2020-12-01 01:09

    You can use recursion:

    Node* MergeLists(Node *headA, Node* headB)
    {
    
    if(headA==NULL){
        return headB;
    }else if(headB ==NULL){
        return headA;
    }
    Node* head = NULL;
    if(headA->data <= headB->data){
        head= headA;
        head->next = MergeLists(headA->next,headB);
    }else{
        head= headB;
        head->next = MergeLists(headA,headB->next);
    }
     return head;
    }
    
    0 讨论(0)
提交回复
热议问题