-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathflatten-a-linked-list.cpp
90 lines (81 loc) · 1.91 KB
/
flatten-a-linked-list.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
// Question: https://www.codingninjas.com/codestudio/problems/flatten-a-linked-list_1112655
#include <bits/stdc++.h>
using namespace std;
/****************************************************************
Following is the class structure of the Node class:
class Node {
public:
int data;
Node* next;
Node* child;
Node(int data) {
this->data = data;
this->next = NULL;
this->child = NULL;
}
};
*****************************************************************/
int len(Node* head) {
Node* temp = head;
int cnt = 0;
while(temp) {
cnt++;
temp = temp->next;
}
return cnt;
}
void display (Node* ans) {
Node* temp = ans;
while(temp) {
cout << temp->data << " ";
temp = temp->next;
}
cout << endl;
}
Node* merge(Node* down, Node* right) {
if(down == NULL)
return right;
if(right == NULL)
return down;
Node* ans = new Node(-1);
Node* temp = ans;
//merge 2 sorted Linked List
while(down != NULL && right != NULL) {
if(down -> data < right -> data ) {
temp -> next = down;
temp = down;
down = down -> child;
}
else
{
temp -> next = right;
temp = right;
right = right -> next;
}
}
while(down != NULL) {
temp -> next = down;
temp = down;
down = down -> child;
}
while(right != NULL) {
temp -> next = right;
temp = right;
right = right -> next;
}
ans = ans -> next;
return ans;
}
Node* flattenLinkedList(Node* head) {
if(head == NULL || head->next == NULL) {
cout << "Test returned at " << head->data << endl;
return head;
}
Node* down = head;
Node* right = flattenLinkedList(head->next);
down->next = NULL;
Node* ans = merge(down, right);
cout << "Test: ";
display(ans);
return ans;
}