Python Program For Flattening A Linked List
Last Updated :
13 Jun, 2022
Given a linked list where every node represents a linked list and contains two pointers of its type:
- Pointer to next node in the main list (we call it 'right' pointer in the code below).
- Pointer to a linked list where this node is headed (we call it the 'down' pointer in the code below).
All linked lists are sorted. See the following example
5 -> 10 -> 19 -> 28
| | | |
V V V V
7 20 22 35
| | |
V V V
8 50 40
| |
V V
30 45
Write a function flatten() to flatten the lists into a single linked list. The flattened linked list should also be sorted. For example, for the above input list, output list should be 5->7->8->10->19->20->22->28->30->35->40->45->50.
The idea is to use the Merge() process of merge sort for linked lists. We use merge() to merge lists one by one. We recursively merge() the current list with the already flattened list.
The down pointer is used to link nodes of the flattened list.
Below is the implementation of the above approach:
Python3
# Python program for flattening
# a Linked List
class Node():
def __init__(self, data):
self.data = data
self.right = None
self.down = None
class LinkedList():
def __init__(self):
# Head of list
self.head = None
# Utility function to insert a
# node at beginning of the
# linked list
def push(self, head_ref, data):
# 1 & 2: Allocate the Node &
# Put in the data
new_node = Node(data)
# Make next of new Node as head
new_node.down = head_ref
# 4. Move the head to point to
# new Node
head_ref = new_node
# 5. Return to link it back
return head_ref
def printList(self):
temp = self.head
while(temp != None):
print(temp.data, end = " ")
temp = temp.down
print()
# An utility function to merge two
# sorted linked lists
def merge(self, a, b):
# If the first linked list is empty
# then second is the answer
if(a == None):
return b
# If second linked list is empty
# then first is the result
if(b == None):
return a
# Compare the data members of the
# two linked lists and put the
# larger one in the result
result = None
if (a.data < b.data):
result = a
result.down =
self.merge(a.down,b)
else:
result = b
result.down =
self.merge(a,b.down)
result.right = None
return result
def flatten(self, root):
# Base Case
if(root == None or
root.right == None):
return root
# Recur for list on right
root.right =
self.flatten(root.right)
# Now merge
root =
self.merge(root, root.right)
# Return the root
# It will be in turn merged with
# its left
return root
# Driver code
L = LinkedList()
'''
Let us 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
'''
L.head = L.push(L.head, 30);
L.head = L.push(L.head, 8);
L.head = L.push(L.head, 7);
L.head = L.push(L.head, 5);
L.head.right =
L.push(L.head.right, 20);
L.head.right =
L.push(L.head.right, 10);
L.head.right.right =
L.push(L.head.right.right, 50);
L.head.right.right =
L.push(L.head.right.right, 22);
L.head.right.right =
L.push(L.head.right.right, 19);
L.head.right.right.right =
L.push(L.head.right.right.right, 45);
L.head.right.right.right =
L.push(L.head.right.right.right, 40);
L.head.right.right.right =
L.push(L.head.right.right.right, 35);
L.head.right.right.right =
L.push(L.head.right.right.right, 20);
# Flatten the list
L.head = L.flatten(L.head);
L.printList()
# This code is contributed by maheshwaripiyush9
Output:
5 7 8 10 19 20 20 22 30 35 40 45 50
Time Complexity: O(N*N*M) – where N is the no of nodes in main linked list (reachable using right pointer) and M is the no of node in a single sub linked list (reachable using down pointer).
Space Complexity: O(N*M) as the recursive functions will use recursive stack of size equivalent to total number of elements in the lists.
Please refer complete article on Flattening a Linked List for more details!
Similar Reads
Flattening a Linked List Given a Linked List of size n, where every node represents a sub-linked-list and contains two pointers:next pointer to the next nodebottom pointer to a linked list where this node is head.Each of the sub-linked-list is in sorted order. Flatten the Link List such that all the nodes appear in a single
15+ min read
Pretty print Linked List in Python Creating custom data types can be tricky, especially when you want to use it like any other data type. Linked List can be thought of as an example of a custom data type. In other languages, if you want to print the linked list, you would define a separate print function, something like pprint but it
3 min read
Python Library for Linked List Linked list is a simple data structure in programming, which obviously is used to store data and retrieve it accordingly. To make it easier to imagine, it is more like a dynamic array in which data elements are linked via pointers (i.e. the present record points to its next record and the next one p
5 min read
Implementation of XOR Linked List in Python Prerequisite: XOR Linked List An ordinary Doubly Linked List requires space for two address fields to store the addresses of previous and next nodes. A memory-efficient version of Doubly Linked List can be created using only one space for the address field with every node. This memory efficient Doub
6 min read
Doubly Linked List in Python Doubly Linked List is a type of linked list in which each node contains a data element and two links pointing to the next and previous node in the sequence. This allows for more efficient operations such as traversals, insertions, and deletions because it can be done in both directions. Table of Con
13 min read
Python Linked List In this article, we will learn about the implementation of a linked list in Python. To implement the linked list in Python, we will use classes in Python. Now, we know that a linked list consists of nodes and nodes have two elements i.e. data and a reference to another node. Let's implement the node
13 min read