-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathflattenlist.cpp
106 lines (89 loc) · 1.96 KB
/
flattenlist.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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
#include <iostream>
using namespace std;
struct Node
{
int data;
Node* next;
Node* down;
Node(int data)
{
this->data = data;
this->next = this->down = nullptr;
}
};
void printOriginalList(Node* head)
{
if (head == nullptr) {
return;
}
cout << ' ' << head->data << ' ';
if (head->down)
{
cout << "[";
printOriginalList(head->down);
cout << "]";
}
printOriginalList(head->next);
}
void printFlatenedList(Node* head)
{
while (head)
{
cout << head->data << " -> ";
head = head->next;
}
cout << "null" << '\n';
}
Node* flattenList(Node* head)
{
if (head == nullptr) {
return nullptr;
}
Node* next = head->next;
head->next = flattenList(head->down);
Node* tail = head;
while (tail->next) {
tail = tail->next;
}
tail->next = flattenList(next);
return head;
}
int main()
{
Node* one = new Node(1);
Node* two = new Node(2);
Node* three = new Node(3);
Node* four = new Node(4);
Node* five = new Node(5);
Node* six = new Node(6);
Node* seven = new Node(7);
Node* eight = new Node(8);
Node* nine = new Node(9);
Node* ten = new Node(10);
Node* eleven = new Node(11);
Node* twelve = new Node(12);
Node* thirteen = new Node(13);
Node* fourteen = new Node(14);
Node* fifteen = new Node(15);
Node* head = one;
one->next = four;
four->next = fourteen;
fourteen->next = fifteen;
five->next = nine;
nine->next = ten;
seven->next = eight;
eleven->next = thirteen;
one->down = two;
two->down = three;
four->down = five;
five->down = six;
six->down = seven;
ten->down = eleven;
eleven->down = twelve;
cout << "The original list is :" << '\n';
printOriginalList(head);
head = flattenList(head);
cout << "\n\nThe flattened list is :" << '\n';
printFlatenedList(head);
return 0;
}