Merge Two Sorted Linked Lists in C++

This C++ program demonstrates how to merge two sorted linked lists into a single sorted linked list. The implementation uses a simple linked list structure where each node contains an integer data and a pointer to the next node.

Program Code


#include <iostream>

// Definition for singly-linked list.
struct ListNode {
    int val;
    ListNode *next;
    ListNode(int x) : val(x), next(NULL) {}
};

// Function to merge two sorted linked lists
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
    if (!l1) return l2;
    if (!l2) return l1;

    // Ensure that l1 is the list starting with the smaller element
    if (l1->val > l2->val) std::swap(l1, l2);

    // Start from the first list
    ListNode* result = l1;

    while (l1 != NULL && l2 != NULL) {
        ListNode* tmp = NULL;
        // Traverse the list until finding the place to insert elements from l2
        while (l1 != NULL && l1->val <= l2->val) {
            tmp = l1;
            l1 = l1->next;
        }
        // Now l1 is the first element greater than the current l2 element
        // Insert l2 here
        tmp->next = l2;
        std::swap(l1, l2);
    }

    return result;
}

// Helper function to print the linked list
void printList(ListNode* node) {
    while (node != NULL) {
        std::cout << node->val << " ";
        node = node->next;
    }
    std::cout << std::endl;
}

int main() {
    // Create first sorted linked list: 1->2->4
    ListNode* a = new ListNode(1);
    a->next = new ListNode(2);
    a->next->next = new ListNode(4);

    // Create second sorted linked list: 1->3->4
    ListNode* b = new ListNode(1);
    b->next = new ListNode(3);
    b->next->next = new ListNode(4);

    // Merge the lists
    ListNode* mergedList = mergeTwoLists(a, b);
    std::cout << "Merged List: ";
    printList(mergedList);

    return 0;
}

Explanation of the Code

The program includes a struct definition for the linked list node, which consists of an integer value and a pointer to the next node. The function mergeTwoLists() takes two sorted linked lists and merges them. It handles the cases where one of the lists is empty, ensuring stability and maintaining order.

The merging process checks each node and inserts nodes from the second list into the first list at the appropriate positions. This is done by adjusting pointers without creating new nodes, thus being memory efficient. The helper function printList() is used to display the merged list.

Conclusion

This C++ program efficiently merges two sorted linked lists using a simple and understandable algorithm. The approach ensures that no additional memory is allocated for the nodes, and the existing nodes are reused.

 

By Aditya Bhuyan

I work as a cloud specialist. In addition to being an architect and SRE specialist, I work as a cloud engineer and developer. I have assisted my clients in converting their antiquated programmes into contemporary microservices that operate on various cloud computing platforms such as AWS, GCP, Azure, or VMware Tanzu, as well as orchestration systems such as Docker Swarm or Kubernetes. For over twenty years, I have been employed in the IT sector as a Java developer, J2EE architect, scrum master, and instructor. I write about Cloud Native and Cloud often. Bangalore, India is where my family and I call home. I maintain my physical and mental fitness by doing a lot of yoga and meditation.

Leave a Reply

Your email address will not be published. Required fields are marked *

error

Enjoy this blog? Please spread the word :)