-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
flat a linkedlist.cpp
68 lines (61 loc) · 1.48 KB
/
flat 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
57
58
59
60
61
62
63
64
65
66
67
68
#include <iostream>
using namespace std;
class node {
public:
int data;
node* next;
node* child;
node() {
data = 0;
child = NULL;
next = NULL;
}
node(int val) {
data = val;
next = NULL;
child = NULL;
}
};
node* FlatList(node* head) {
if (head == NULL) {
return NULL;
}
node* current = head;
while (current) {
if (current->child) {
node* nextNode = current->next;
current->next = FlatList(current->child);
current->child = nullptr;
while (current->next) {
current = current->next;
}
current->next = nextNode;
if (nextNode) {
nextNode->child = nullptr;
}
}
current = current->next;
}
return head;
}
void Print(node* head) {
node* current = head;
while (current) {
std::cout << current->data << "->";
current = current->next;
}
cout << "NULL" << std::endl;
}
int main() {
node* head = new node(1);
head->next = new node(2);
head->next->next = new node(3);
head->next->child = new node(4);
head->next->child->next = new node(5);
head->next->child->next->child = new node(6);
head->next->next->child = new node(7);
head->next->next->child->next = new node(8);
node* List = FlatList(head);
Print(List);
return 0;
}