-
Notifications
You must be signed in to change notification settings - Fork 0
/
21. Merge Two Sorted Lists.c
60 lines (56 loc) · 1.55 KB
/
21. Merge Two Sorted Lists.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
struct ListNode {
int val;
struct ListNode *next;
};
struct ListNode* mergeTwoLists(struct ListNode* l1, struct ListNode* l2) {
struct ListNode *list = NULL;
struct ListNode *pointer = NULL;
struct ListNode *pointer1 = l1;
struct ListNode *pointer2 = l2;
while (pointer1 && pointer2) {
struct ListNode *node = (struct ListNode *)malloc(sizeof(struct ListNode));
if (pointer1->val > pointer2->val) {
node->val = pointer2->val;
node->next= NULL;
pointer2 = pointer2->next;
} else {
node->val = pointer1->val;
node->next= NULL;
pointer1 = pointer1->next;
}
if (pointer) {
pointer->next = node;
}
pointer = node;
if (!list) {
list = pointer;
}
}
while (pointer1) {
struct ListNode *node = (struct ListNode *)malloc(sizeof(struct ListNode));
node->val = pointer1->val;
node->next= NULL;
pointer1 = pointer1->next;
if (pointer) {
pointer->next = node;
}
pointer = node;
if (!list) {
list = pointer;
}
}
while (pointer2) {
struct ListNode *node = (struct ListNode *)malloc(sizeof(struct ListNode));
node->val = pointer2->val;
node->next= NULL;
pointer2 = pointer2->next;
if (pointer) {
pointer->next = node;
}
pointer = node;
if (!list) {
list = pointer;
}
}
return list;
}