-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFlatten_a_LinkedList.cpp
56 lines (53 loc) · 1.1 KB
/
Flatten_a_LinkedList.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
/*
* Definition for linked list.
* class Node {
* public:
* int data;
* Node *next;
* Node *child;
* Node() : data(0), next(nullptr), child(nullptr){};
* Node(int x) : data(x), next(nullptr), child(nullptr) {}
* Node(int x, Node *next, Node *child) : data(x), next(next), child(child) {}
* };
*/
Node *mergeList(Node *a, Node *b)
{
Node *temp = new Node(-1);
Node *res = temp;
if (!a)
return b;
if (!b)
return a;
while (a && b)
{
if (a->data < b->data)
{
temp->child = a;
temp = temp->child;
a = a->child;
}
else
{
temp->child = b;
temp = temp->child;
b = b->child;
}
}
if (a)
temp->child = a;
else
temp->child = b;
return res->child;
}
Node *flattenLinkedList(Node *head)
{
// Write your code here
if (!head)
return head;
Node *down = head;
Node *right = head->next;
down->next = NULL;
right = flattenLinkedList(right);
Node *ans = mergeList(down, right);
return ans;
}