Flattening a Linked List in C++



In this problem, we are given linked list consisting of two pointer nodes, right and down.

  • Right node is the main linked list pointer.

  • Down node is for secondary linked list starting with that node.

All the linked lists are sorted.

Our task is to create a program to flatten a linked list and the resulting list will itself be a sorted one.

Let’s take an example to understand the problem

Input

Output

1-> 9-> 8 -> 4 -> 6-> 7-> 2-> 3-> 5

Solution Approach

A solution to the problem is using merge sort for a linked list. This method will merge the lists recursively in a sorted order to form a flattened list.

Example

Program to illustrate the working of our solution

Open Compiler
#include <bits/stdc++.h> using namespace std; class Node{ public: int data; Node *right, *down; }; Node* head = NULL; Node* mergeList(Node* a, Node* b){ if (a == NULL) return b; if (b == NULL) return a; Node* result; if (a->data < b->data){ result = a; result->down = mergeList(a->down, b); } else{ result = b; result->down = mergeList(a, b->down); } result->right = NULL; return result; } Node* flattenLinkedList(Node* root){ if (root == NULL || root->right == NULL) return root; root->right = flattenLinkedList(root->right); root = mergeList(root, root->right); return root; } Node* push(Node* head_ref, int data){ Node* new_node = new Node(); new_node->data = data; new_node->right = NULL; new_node->down = head_ref; head_ref = new_node; return head_ref; } int main(){ head = push(head, 7); head = push(head, 1); head->right = push(head->right, 11); head->right = push(head->right, 5); head->right = push(head->right, 4); head->right->right = push(head->right->right, 12); head->right->right = push(head->right->right, 6); head->right->right->right = push(head->right->right->right, 8); head->right->right->right->right = push(head->right->right->right->right, 16); head = flattenLinkedList(head); cout<<"The Flattened Linked list is : \n"; Node* temp = head; while (temp != NULL){ cout<<temp->data<<" => "; temp = temp->down; } cout<<"NULL"; return 0; }

Output

The Flattened Linked list is :
1 => 4 => 5 => 6 => 7 => 8 => 11 => 12 => 16 => NULL
Updated on: 2022-02-01T06:41:02+05:30

439 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements