From 0bf3d8e3b4f008e227e5e09544f8aca4829b4639 Mon Sep 17 00:00:00 2001 From: priyanshuanand166 <73073489+priyanshuanand166@users.noreply.github.com> Date: Thu, 13 Oct 2022 17:51:13 +0530 Subject: [PATCH] flatteningALinkedlist.cpp 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 Pointer to a linked list where this node is headed. --- Linked List/flatteningALinkedlist.cpp | 79 +++++++++++++++++++++++++++ 1 file changed, 79 insertions(+) create mode 100644 Linked List/flatteningALinkedlist.cpp diff --git a/Linked List/flatteningALinkedlist.cpp b/Linked List/flatteningALinkedlist.cpp new file mode 100644 index 0000000..e839416 --- /dev/null +++ b/Linked List/flatteningALinkedlist.cpp @@ -0,0 +1,79 @@ +#include +using namespace std; + +// Linked list Node +struct Node { + int data; + struct Node* next; + struct Node* bottom; + + Node(int x) + { + data = x; + next = NULL; + bottom = NULL; + } +}; + +// comparator function for priority queue +struct mycomp { + bool operator()(Node* a, Node* b) + { + return a->data > b->data; + } +}; + +void flatten(Node* root) +{ + priority_queue, mycomp> p; + // pushing main link nodes into priority_queue. + while (root != NULL) { + p.push(root); + root = root->next; + } + + // Extracting the minimum node + // while priority queue is not empty + while (!p.empty()) { + + // extracting min + auto k = p.top(); + p.pop(); + + // printing least element + cout << k->data << " "; + if (k->bottom) + p.push(k->bottom); + } +} + +int main() +{ + Node* head = new Node(5); + auto temp = head; + auto bt = head; + bt->bottom = new Node(7); + bt->bottom->bottom = new Node(8); + bt->bottom->bottom->bottom = new Node(30); + temp->next = new Node(10); + + temp = temp->next; + bt = temp; + bt->bottom = new Node(20); + temp->next = new Node(19); + temp = temp->next; + bt = temp; + bt->bottom = new Node(22); + bt->bottom->bottom = new Node(50); + temp->next = new Node(28); + temp = temp->next; + bt = temp; + bt->bottom = new Node(35); + bt->bottom->bottom = new Node(40); + bt->bottom->bottom->bottom = new Node(45); + + // Function call + flatten(head); + cout << endl; + return 0; +}