Skip to content

Instantly share code, notes, and snippets.

@sauravgpt
Created June 10, 2021 12:22
Show Gist options
  • Save sauravgpt/a7d3e2e6fe2b9364c07d310fe84c0f25 to your computer and use it in GitHub Desktop.
Save sauravgpt/a7d3e2e6fe2b9364c07d310fe84c0f25 to your computer and use it in GitHub Desktop.
Flattening a Linked List
/*
https://practice.geeksforgeeks.org/problems/flattening-a-linked-list/1#
struct Node{
int data;
struct Node * next;
struct Node * bottom;
Node(int x){
data = x;
next = NULL;
bottom = NULL;
}
};
*/
/* Function which returns the root of
the flattened linked list. */
void merge(Node *l1, Node *l2) {
Node *curr = l1;
l1 = l1->bottom;
while(l1 && l2) {
if(l1->data < l2->data) {
curr->bottom = l1;
l1 = l1->bottom;
} else {
curr->bottom = l2;
l2 = l2->bottom;
}
curr = curr->bottom;
}
if(l1) curr->bottom = l1;
if(l2) curr->bottom = l2;
}
Node *flatten(Node *node)
{
Node *dummy = new Node(0);
Node *prev = node;
while(node) {
merge(dummy, node);
node = node->next;
prev->next = nullptr;
}
dummy->next = nullptr;
return dummy->bottom;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment