ronith
7/9/2018 - 7:02 AM

Merge two sorted linked lists such that merged list is in reverse order

Given two linked lists sorted in increasing order. Merge them such a way that the result list is in decreasing order (reverse order).

Examples:

Input: a: 5->10->15->40 b: 2->3->20 Output: res: 40->20->15->10->5->3->2

Input: a: NULL b: 2->3->20 Output: res: 20->3->2

// https://www.geeksforgeeks.org/merge-two-sorted-linked-lists-such-that-merged-list-is-in-reverse-order/
#include <iostream>
#include <list>
using namespace std;

struct linked_list {
    int data;
    struct linked_list *next;
};
typedef struct linked_list node;

void print(node* n) {
    while (n) {
        cout<< n->data << "->";
        n = n->next;
    }
    cout<< "NULL";
    return;
}

node* insert (node* head, int n) {
    node* list = new node;
    list->data = n;
    if (head == NULL) {
        list->next = head;
        head = list;
        return head;
    }
    list->next = NULL;
    node* last= head;
    while (last->next != NULL )
        last = last->next;
    last->next = list;
    return head;
}

node* push (node* head, int n) {
    node* temp = new node;
    temp->data = n;
    temp->next = head;
    head = temp;
    return head;
}

node* reversemerge(node* head1, node* head2) {
    node* head = NULL;
    while (head1 && head2) {
        if (head1->data <= head2->data) {
            head=push(head,head1->data);
            head1=head1->next;
        }
        else {
            head=push (head, head2->data);
            head2 = head2->next;
        }
    }
    while (head1) {
        head=push(head, head1->data);
        head1=head1->next;
    }
    while (head2) {
        head=push(head, head2->data);
        head2=head2->next;
    }
    return head;
}

int main() {
    int n;
    node* head1 = NULL, *head2=NULL, *head3;
    cout<< "Enter the first list: \n";
    while (true) {
        cout<< "Enter the elements, and -999 to stop: ";
        cin>>n;
        if (n==-9)
            break;
        else
            head1=insert(head1,n);
    }
    cout<< "Enter the second list: \n";
    while (true) {
        cout<< "Enter the elements, and -999 to stop: ";
        cin>>n;
        if (n==-9)
            break;
        else
            head2=insert(head2,n);
    }
    print(head1);
    cout << "\n";
    print(head2);
    cout << "\n";
    head3 = reversemerge(head1,head2);
    print(head3);
}