forked from lennylxx/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
21.c
97 lines (81 loc) · 1.95 KB
/
21.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
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
#include <stdio.h>
#include <stdlib.h>
struct ListNode {
int val;
struct ListNode *next;
};
struct ListNode* mergeTwoLists(struct ListNode* l1, struct ListNode* l2) {
if (l1 == NULL) return l2;
if (l2 == NULL) return l1;
struct ListNode *p1 = l1;
struct ListNode *p2 = l2;
struct ListNode *ret = NULL;
struct ListNode **p = &ret;
while (1) {
if (p1 && p2) {
if (p1->val <= p2->val) {
*p = p1;
p1 = p1->next;
}
else {
*p = p2;
p2 = p2->next;
}
}
else if (p1 && p2 == NULL) {
*p = p1;
p1 = p1->next;
}
else if (p2 && p1 == NULL) {
*p = p2;
p2 = p2->next;
}
else break;
p = &((*p)->next);
}
return ret;
}
int main() {
struct ListNode *headA
= (struct ListNode *)calloc(5, sizeof(struct ListNode));
struct ListNode *headB
= (struct ListNode *)calloc(3, sizeof(struct ListNode));
struct ListNode **p = &headA;
int i;
for (i = 1; i <= 5; i++) {
(*p)->val = i;
(*p)->next = *p + 1;
p = &(*p)->next;
}
*p = NULL;
p = &headB;
for (i = 3; i <= 7; i += 2) {
(*p)->val = i;
(*p)->next = *p + 1;
p = &(*p)->next;
}
*p = NULL;
printf("List A: ");
struct ListNode *q = headA;
while (q != NULL) {
printf("%d->", q->val);
q = q->next;
}
printf("N\n");
printf("List B: ");
q = headB;
while (q) {
printf("%d->", q->val);
q = q->next;
}
printf("N\n");
struct ListNode *ret = mergeTwoLists(headA, headB);
printf("Merged: ");
q = ret;
while (q) {
printf("%d->", q->val);
q = q->next;
}
printf("N\n");
return 0;
}