-
Notifications
You must be signed in to change notification settings - Fork 0
/
flattenLinkedList.c
60 lines (54 loc) · 1.27 KB
/
flattenLinkedList.c
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
#include <stdio.h>
#include <stdlib.h>
typedef struct elementT {
struct elementT *right;
struct elementT *down;
int data;
} element;
element *merge(element *a, element *b) {
if(a == NULL)
return b;
else if(b == NULL)
return a;
element *ele;
if(a->data < b->data) {
ele = a;
ele->down = merge(a->down, b);
} else {
ele = b;
ele->down = merge(a, b->down);
}
return ele;
}
element *flatten(element *root) {
if(root == NULL || root->right == NULL)
return root;
return merge(root, flatten(root->right));
}
element *makeNode(int d) {
element *ele = (element *)malloc(sizeof(element));
ele->data = d;
return ele;
}
void printList(element *h) {
while(h) {
printf("%d ", h->data);
h = h->down;
}
printf("\n");
}
main()
{
element *root = makeNode(4);
root->down = makeNode(6);
root->down->down = makeNode(7);
root->down->down->down = makeNode(10);
root->right = makeNode(5);
root->right->down = makeNode(8);
root->right->down->down = makeNode(9);
root->right->down->down->down = makeNode(15);
root->right->right = makeNode(20);
root->right->right->right = makeNode(22);
element *e = flatten(root);
printList(e);
}