×

Flattening a Linked List

In this article, we are going to study about the logic behind the flattening of linked list and we also going to build a code in the C++ to flatten a given linked list. In this challenge, we are given a linked list with the right and down pointer nodes. Main linked list pointer is located at right node. The secondary linked list is for the node at the bottom of the list.

Approach for the program

We can use merge sort to combine all the sub-lists into a single list because each sub-list in the linked list is in sorted order.

The following steps make up this algorithm:

  • A two-pointer to a dummy node should be created. As we merge the linked list, one pointer is used to maintain track of the dummy node and the second pointer is utilized to advance.
  • Using the merging algorithm of the merge sort, select any two sub-linked lists and run through the list to combine them.
  • Return the final list after combining all sub-lists into one.

C++ Example for flattening a linked list

// C++ program for flattening a
// Linked List
#include <bits/stdc++.h>
using namespace std;


// Link list node
class Node
{
	public:
	int data;
	Node *right, *down;
};


Node* head = NULL;


Node* merge(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 = merge(a->down, b);
	}


	else
	{
		result = b;
		result->down = merge(a, b->down);
	}
	result->right = NULL;
	return result;
}


Node* flatten(Node* root)
{
	// Base Cases
	if (root == NULL ||
		root->right == NULL)
		return root;


	// Recur for list on right
	root->right = flatten(root->right);


	// Now merge
	root = merge(root, root->right);


	// Return the root
	// It will be in turn merged
	// with its left
	return root;
}


// Utility function to insert a node at
// beginning of the linked list
Node* push(Node* head_ref, int data)
{
	// Allocate the Node &
	// Put in the data
	Node* new_node = new Node();


	new_node->data = data;
	new_node->right = NULL;


	// Make next of new Node as head
	new_node->down = head_ref;


	// Move the head to point to
	// new Node
	head_ref = new_node;


	return head_ref;
}
void printList()
{
	Node* temp = head;
	while (temp != NULL)
	{
		cout << temp->data << " ";
		temp = temp->down;
	}
	cout << endl;
}
int main()
{
	/* Create the following linked list
		5 -> 10 -> 19 -> 28
		| |	 |	 |
		V V	 V	 V
		7 20 22 35
		|		 |	 |
		V		 V	 V
		8		 50 40
		|			 |
		V			 V
		30			 45
	*/
	head = push(head, 30);
	head = push(head, 8);
	head = push(head, 7);
	head = push(head, 5);


	head->right = push(head->right, 20);
	head->right = push(head->right, 10);


	head->right->right =
	push(head->right->right, 50);
	head->right->right =
	push(head->right->right, 22);
	head->right->right =
	push(head->right->right, 19);


	head->right->right->right =
	push(head->right->right->right, 45);
	head->right->right->right =
	push(head->right->right->right, 40);
	head->right->right->right =
	push(head->right->right->right, 35);
	head->right->right->right =
	push(head->right->right->right, 20);


	// Flatten the list
	head = flatten(head);


	printList();
	return 0;
}

Output:

5 7 8 10 19 20 20 22 30 35 40 45 50

The flattened linked list it above has all of its components arranged in alphabetical order. Two techniques, which are further described in this article, can flatten a linked list.

Time Complexity

The formula is O(N * N * M), where N is the number of nodes in the primary linked list and M is the number of nodes in a single sub-linked list.

Explanation of time complexity

  • Two lists are being combined at once.
  • The time required will be O(M+M) = O after combining the first two lists (2M).
  • After that, we will merge a second list with the one above it (3M).
  • Then we shall combine another list, making time equal to O(3M + M).
  • The process of combining lists will continue until all lists have been combined.
  • O(2M + 3M + 4M +.... N*M) = (2M + 3M + 4M +.... N*M) * M will be the total amount of time required.
  • Time = O(((N * N + N - 2) * M/2) using the arithmetic sum formula.
  • For a large value of N, the preceding expression generally equals O(N * N * M).

Related Topics

Rearrange a linked list into alternate fashion first and the last element

Rearrange a linked list into alternate fashion first and the last element This article will explain how to rearrange the linked list into alternate fashion first and the last element. Here,...

3 minutes read.

Blowfish algorithm

The Blowfish algorithm is the very first encryption algorithm which is symmetric. It was firstly used as an alternate algorithm for the DES algorithm. It was designed by Bruce Steiner...

3 minutes read.

String Operations in Data Structures

Operations on Strings Reversing the order of words in a sentence Reversing a string is a technique that reverses or alters the order of a given string so that the last character...

9 minutes read.

Number of visible boxes putting one inside another

You have given one array, which consists of values which represent the sizes of different boxes. We can put one box inside another if the size of the outside box...

3 minutes read.

Strings in Data Structures

Strings and functions in C A string is a collection of characters. We'll learn how to declare strings, operate with strings in C programming, and use pre-defined string handling routines. We'll look...

7 minutes read.

Finding the Maximum Element in a Binary Tree

Implementation // Creating a C++ program to excavate the minimum and maximum in a given binary tree. #include <bits/stdc++.h> #include <iostream> using namespace std; // creating a new tree node. class __nod { public: int record; __nod *Lft, *Rt; /*...

4 minutes read.

Selection Sort

In each iteration of the selection sort algorithm, the smallest item from an unsorted list is chosen and placed at the top of the unsorted list. Algorithm of Selection Sorting In order...

3 minutes read.

Find Bridges in a Graph

You have been given a graph. You have to find out the bridges in that graph. Graph may be connected or disconnected. You have to print vertices of particular edge...

4 minutes read.

What is a Sparse Matrix in Data Structure?

Definition A matrix in which a few non-zero elements are present is called a Sparse matrix. In a Sparse matrix, almost all the matrices are filled with zero (0). A matrix...

5 minutes read.

How to Start Learning DSA

All programmer experiences a point along the way where they wish they could approach a problem in a more effective manner. They finally learn about the terminology DSA while trying...

10 minutes read.

Bubble sort algorithm using Javascript

Sorting is a very useful technique in many algorithms and programs. Basically, sorting operations help us to arrange a set of data in a particular manner. Bubble sort is one...

3 minutes read.

LCA of binary tree

Implementation //Writing a program to find the lowest common factor in a given binary search tree. #include <iostream> #include <vector> using namespace std; // the very first step is to create a binary tree. struct __nod { int...

8 minutes read.

Serialize and Deserialize Binary Trees

In order to save a tree in a file that can later be restored, serialisation is used. The tree's structure must be preserved. Deserialization involves reading a tree from a...

4 minutes read.

Bubble Sort vs Selection Sort

In this article, we will discuss the basic differences between these two sorting algorithms. Let us have a quick overview of what these sorting algorithms are? And what are the...

6 minutes read.

What is a full Binary Tree?

A full binary tree is considered to be a special kind of binary tree in which every single node or leaf node present either contains two children or no children...

4 minutes read.

B+ Tree Program in Q language

A B+ tree is just an improvised version of a self-balancing and well-maintained tree in which all the key values that hold valuable information is present at the bottom, which...

9 minutes read.

Construction of B tree in Data Structure

A B-tree is a type of balanced tree data structure that is commonly used in file systems and databases to improve the efficiency of search, insert, and delete operations. The structure...

4 minutes read.

Convert a Binary Tree into a Binary Search Tree

Implementation #include <stdio.h>   #include <stdlib.h>       //creating a node of the binary tree.  struct __nod{       int record;       struct __nod *Lft;       struct __nod *Rt;   };       // presenting the root of the binary tree.   struct...

5 minutes read.

Fundamental of Algorithms

An algorithm is a part of any programming solution or coding. If we have to make a solution then first we have to think of a clear idea about the...

13 minutes read.

Merge Conflicts and ways to handle them

Merge Conflicts Whenever dealing with the Git merge operations, conflicts will be the frequently occurred. When more than two developers work on the same file on different systems using Git, they...

4 minutes read.