Skip to content

Commit 6c117a1

Browse files
add problem 21 and test function
1 parent 9e7efbf commit 6c117a1

File tree

1 file changed

+59
-0
lines changed

1 file changed

+59
-0
lines changed

C/1-50/21-Merge-Two-Sorted-Lists.c

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
/*
2+
* Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.
3+
* Created by supercoderx on 2017/8/10.
4+
*/
5+
6+
#include
7+
#include
8+
#include "../main.h"
9+
10+
struct ListNode* mergeTwoLists(struct ListNode* l1, struct ListNode* l2) {
11+
struct ListNode *p1 = l1,*p2=l2, *header=NULL,*p3=NULL,*node=NULL;
12+
if(l1==NULL || l2 == NULL){
13+
return l1==NULL?l2:l1;
14+
}
15+
16+
while (p1!=NULL || p2!=NULL){
17+
node = malloc(sizeof(struct ListNode));
18+
node->next = NULL;
19+
if(p1==NULL){
20+
node->val = p2->val;
21+
p3->next = node;
22+
p3 = node;
23+
p2=p2->next;
24+
}
25+
else if(p2==NULL){
26+
node->val = p1->val;
27+
p3->next = node;
28+
p3 = node;
29+
p1=p1->next;
30+
} else{
31+
if(p1->val<p2->val){
32+
node->val = p1->val;
33+
p1=p1->next;
34+
}else{
35+
node->val = p2->val;
36+
p2=p2->next;
37+
}
38+
if(header == NULL){
39+
header = node;
40+
}else{
41+
p3->next = node;
42+
}
43+
p3 = node;
44+
}
45+
}
46+
return header;
47+
}
48+
49+
void testMergeTwoLists(){
50+
int a1[]={1,2,3},b1[]={4,5,6};
51+
int a2[]={1,9,10},b2[]={2,3,4,6,7};
52+
struct ListNode * la1 = createList(a1,3);
53+
struct ListNode * lb1 = createList(b1,3);
54+
struct ListNode * la2 = createList(a2,3);
55+
struct ListNode * lb2 = createList(b2,5);
56+
printList(mergeTwoLists(la1,lb1));
57+
printList(mergeTwoLists(la2,lb2));
58+
59+
}

0 commit comments

Comments
 (0)