- Notifications
You must be signed in to change notification settings - Fork 117
/
Copy path21.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>
structListNode {
intval;
structListNode*next;
};
structListNode*mergeTwoLists(structListNode*l1, structListNode*l2) {
if (l1==NULL) returnl2;
if (l2==NULL) returnl1;
structListNode*p1=l1;
structListNode*p2=l2;
structListNode*ret=NULL;
structListNode**p=&ret;
while (1) {
if (p1&&p2) {
if (p1->val <= p2->val) {
*p=p1;
p1=p1->next;
}
else {
*p=p2;
p2=p2->next;
}
}
elseif (p1&&p2==NULL) {
*p=p1;
p1=p1->next;
}
elseif (p2&&p1==NULL) {
*p=p2;
p2=p2->next;
}
elsebreak;
p=&((*p)->next);
}
returnret;
}
intmain() {
structListNode*headA
= (structListNode*)calloc(5, sizeof(structListNode));
structListNode*headB
= (structListNode*)calloc(3, sizeof(structListNode));
structListNode**p=&headA;
inti;
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: ");
structListNode*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");
structListNode*ret=mergeTwoLists(headA, headB);
printf("Merged: ");
q=ret;
while (q) {
printf("%d->", q->val);
q=q->next;
}
printf("N\n");
return0;
}