×

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

Recursion in Fibonacci

Fibonacci heap is considered to be a particular execution of the heap data structure that ultimately helps in making use of not just any number but the Fibonacci numbers. It...

3 minutes read.

Asynchronous advantage actor-critic (A3C) Algorithm

The Asynchronous advantage actor-critic (A3C) Algorithm is one of the latest algorithms developed by the Artificial Intelligence division, Deep Mind at Google. It is used for the Deep Reinforcement Learning...

3 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.

Types of Linked list

Single linked list  A single linked list is a linked list in which all nodes are connected with each other in sequence. Each node of a singly linked list has two...

7 minutes read.

Data Structures Tutorial

The data structure is a way of storing and organizing data in a computer system. So that we can use the data quickly, which means the information is stored and...

7 minutes read.

Priority Queue in Data Structure

Priority Queue A priority queue is a special kind of queue, in priority queue we give some priority to an element and according to this priority an element can be served...

3 minutes read.

Binary Tree to Doubly Linked List

Binary Tree to Doubly Linked List This article will explain how to convert the given binary tree into a Doubly Linked List. The left and right pointers in tree nodes are...

2 minutes read.

Post-order traversal in a binary tree

We all know that postorder is a form of tree traversal to visit the tree's nodes, and it helps us reach out to the tree's nodes. Postorder means visiting the...

4 minutes read.

Given a Perfect Binary Tree, Reverse Alternate Levels

Implementation //writing a program in C++ language to see how to approach it. #include <bits/stdc++.h> using namespace std; // creating a tree node. struct Nod { char ky; struct Nod *Lft, *Rt; }; // creating a new utility function...

9 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.

Inorder Successor in Binary Trees

The next node in the Inorder traversal of a binary tree is known as Inorder successor of that particular node. In a Binary Search Tree, the definition of Inorder successor can...

9 minutes read.

Structure and Union Data Structure

The array is used for the same type of data, but if we want to store a mixed type of data in a group, then the array cannot be used. The Structure...

4 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.

Given a Binary Tree Check the Zig-Zag Traversal

Implementation // The C++ implementation of the zig-zag traversal method in the O(n) time.  #include <iostream> #include <stack> using namespace std; // creating a binary tree node. struct __nod { int record; struct __nod *Lft, *Rt; }; // creating a...

4 minutes read.

Implementation of Queue

Implementation of queue: We can implement the queue through the array and linked list. An array is the easiest way to implement the queue. When a queue is created with the...

7 minutes read.

Red Black Tree vs AVL Tree: Data Structure

Difference Between Red Black Tree vs AVL Tree Red Black Tree: A red-black tree is referred as self-balancing binary search tree. In red-black, each node stores an extra bit that determines...

4 minutes read.

What is a Tree in Terms of a Graph?

To know the explanation of trees in terms of graphs, we need first to know what trees and graphs are. So let us first learn about trees and graphs. Trees and...

6 minutes read.

Array vs Linked List: Data Structure

Data structure: Difference Between Array and Linked List What is Array? An array is a linear data structure that can store similar data items for further processing. The similar data items...

3 minutes read.

Time Complexity of Selection Sort in Data Structure

What is Time Complexity? The term “Time complexity” can be defined as the number of times executions made of a particular sequence of instructions and not the total amount of time...

3 minutes read.

Insertion in B+ Tree

We will learn how to insert a node in the B+ tree and what are the different properties we are going to follow. Except for the root node, every node should...

5 minutes read.