Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Python Program for Deleting a Node in a Linked List
Next article icon

Python Program For Flattening A Linked List

Last Updated : 13 Jun, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a linked list where every node represents a linked list and contains two pointers of its type: 

  1. Pointer to next node in the main list (we call it 'right' pointer in the code below).
  2. 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.

Recommended: Please solve it on "PRACTICE" first, before moving on to the solution.

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!


Next Article
Python Program for Deleting a Node in a Linked List
author
kartik
Improve
Article Tags :
  • Linked List
  • Python
  • Python Programs
  • DSA
  • Linked Lists
  • Microsoft
  • Amazon
  • Flipkart
  • Goldman Sachs
  • Drishti-Soft
  • Snapdeal
  • Paytm
  • Payu
  • Visa
  • 24*7 Innovation Labs
  • Python-DSA
Practice Tags :
  • 24*7 Innovation Labs
  • Amazon
  • Drishti-Soft
  • Flipkart
  • Goldman Sachs
  • Microsoft
  • Paytm
  • Payu
  • Snapdeal
  • Visa
  • Linked List
  • python

Similar Reads

  • Python Program For Flattening A Multilevel Linked List
    Given a linked list where in addition to the next pointer, each node has a child pointer, which may or may not point to a separate list. These child lists may have one or more children of their own, and so on, to produce a multilevel data structure, as shown in the below figure. You are given the he
    4 min read
  • Python Program for Deleting a Node in a Linked List
    We have discussed Linked List Introduction and Linked List Insertion in previous posts on a singly linked list.Let us formulate the problem statement to understand the deletion process. Given a 'key', delete the first occurrence of this key in the linked list. Iterative Method:To delete a node from
    3 min read
  • Python Program For Rotating A Linked List
    Given a singly linked list, rotate the linked list counter-clockwise by k nodes. Where k is a given positive integer. For example, if the given linked list is 10->20->30->40->50->60 and k is 4, the list should be modified to 50->60->10->20->30->40. Assume that k is smaller than the count of nodes in
    5 min read
  • Python Program For Deleting A Node In A Doubly Linked List
    Pre-requisite: Doubly Link List Set 1| Introduction and Insertion Write a function to delete a given node in a doubly-linked list. Original Doubly Linked List  Recommended: Please solve it on "PRACTICE" first, before moving on to the solution. Approach: The deletion of a node in a doubly-linked list
    4 min read
  • Flatten a List of Lists in Python
    Flattening a list of lists means turning a nested list structure into a single flat list. This can be useful when we need to process or analyze the data in a simpler format. In this article, we will explore various approaches to Flatten a list of Lists in Python. Using itertools.chain itertools modu
    3 min read
  • Python Program For Reversing A Doubly Linked List
    Given a Doubly Linked List, the task is to reverse the given Doubly Linked List. See below diagrams for example.  (a) Original Doubly Linked List (b) Reversed Doubly Linked List Here is a simple method for reversing a Doubly Linked List. All we need to do is swap prev and next pointers for all nodes
    4 min read
  • Python Program For Deleting A Linked List Node At A Given Position
    Given a singly linked list and a position, delete a linked list node at the given position. Example: Input: position = 1, Linked List = 8->2->3->1->7 Output: Linked List = 8->3->1->7 Input: position = 0, Linked List = 8->2->3->1->7 Output: Linked List = 2->3->1
    3 min read
  • Python Program For Inserting A Node In A Linked List
    We have introduced Linked Lists in the previous post. We also created a simple linked list with 3 nodes and discussed linked list traversal.All programs discussed in this post consider the following representations of linked list. Python Code # Node class class Node: # Function to initialize the # n
    7 min read
  • Python Program For Sorting A Linked List Of 0s, 1s And 2s
    Given a linked list of 0s, 1s and 2s, sort it.Examples: Input: 1 -> 1 -> 2 -> 0 -> 2 -> 0 -> 1 -> NULL Output: 0 -> 0 -> 1 -> 1 -> 1 -> 2 -> 2 -> NULL Input: 1 -> 1 -> 2 -> 1 -> 0 -> NULL  Output: 0 -> 1 -> 1 -> 1 -> 2 -> NULL Source: Microsoft Interview | Set 1 Recommended: Please solve it on "PRAC
    3 min read
  • Python Program For Finding The Middle Element Of A Given Linked List
    Given a singly linked list, find the middle of the linked list. For example, if the given linked list is 1->2->3->4->5 then the output should be 3. If there are even nodes, then there would be two middle nodes, we need to print the second middle element. For example, if given linked list
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences