forked from dimpeshmalviya/C-Language-Programs
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathList-Flattening.c
More file actions
106 lines (79 loc) · 1.83 KB
/
List-Flattening.c
File metadata and controls
106 lines (79 loc) · 1.83 KB
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
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node* next;
struct Node* prev;
struct Node* child;
} Node;
void append(Node* child, Node** tail) {
Node* curNode;
(*tail)->next = child;
child->prev = *tail;
for (curNode = child; curNode->next != NULL; curNode = curNode->next)
;
*tail = curNode;
}
void flattenList(Node* head, Node** tail) {
Node* curNode = head;
while (curNode != NULL) {
if (curNode->child) {
append(curNode->child, tail);
curNode->child = NULL;
}
curNode = curNode->next;
}
}
Node* findTail(Node* head) {
Node* tail = head;
while (tail->next != NULL) {
tail = tail->next;
}
return tail;
}
void printList(Node* head) {
Node* cur = head;
while (cur != NULL) {
printf("%d ", cur->data);
cur = cur->next;
}
printf("\n");
}
Node* createNode(int data) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = data;
newNode->next = NULL;
newNode->prev = NULL;
newNode->child = NULL;
return newNode;
}
int main() {
Node* head = createNode(1);
head->next = createNode(2);
head->next->prev = head;
head->next->next = createNode(3);
head->next->next->prev = head->next;
// Create child list for node 1
head->child = createNode(4);
head->child->next = createNode(5);
head->child->next->prev = head->child;
// Create child list for node 3
head->next->next->child = createNode(6);
// Create child list for node 4
head->child->child = createNode(7);
// Find initial tail of top level list
Node* tail = findTail(head);
flattenList(head, &tail);
printList(head);
return 0;
}
/*
Input:
1 <-> 2 <-> 3
| |
4 <-> 5 6
|
7
Output :
1 2 3 4 5 6 7
*/