Answer to Question #270712 in C++ for osama

Question #270712

Write a function that will take two sorted singly linked List as input and merge them in third list. (You are not allowed to use any sorting algorithm) also give main for the function.


1
Expert's answer
2021-11-24T00:41:41-0500
#include <cassert>

template<class T>
struct Node {
    T value;
    Node *next { nullptr };
};

template<class T>
Node<T>* Merge(Node<T> *lhs, Node<T> *rhs) {
    if (!lhs) return rhs;
    if (!rhs) return lhs;

    Node<T> * head = nullptr;
    if (lhs->value < rhs->value) {
        head = lhs;
        lhs = lhs->next;
    }
    else {
        head = rhs;
        rhs = rhs->next;
    }
    Node<T> * node = head;
    while (lhs || rhs) {
        if (lhs && rhs) {
            if (lhs->value < rhs->value) {
                node->next = lhs;
                node = lhs;
                lhs = lhs->next;
            }
            else {
                node->next = rhs;
                node = rhs;
                rhs = rhs->next;
            }
        }
        else {
            assert(lhs || rhs);
            node->next = lhs? lhs: rhs;
            break;
        }
    }
    return head;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS