-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathmerge_two_sorted_list.c
58 lines (43 loc) · 1.05 KB
/
merge_two_sorted_list.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
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
#include<malloc.h>
struct ListNode * insertEnd(struct ListNode *head,int ele){
struct ListNode *p=(struct ListNode *)malloc(sizeof(struct ListNode));
p->val=ele;
p->next=NULL;
if(head==NULL){
head =p;
return head;
}
struct ListNode *q=head;
while(q->next!=NULL)q=q->next;
q->next=p;
return head;
}
struct ListNode* mergeTwoLists(struct ListNode* l1, struct ListNode* l2){
struct ListNode * start=NULL;
while(l1!=NULL && l2!=NULL){
if(l1->val<=l2->val){
start=insertEnd(start,l1->val);
l1=l1->next;
}
else{
start=insertEnd(start,l2->val);
l2=l2->next;
}
}
while(l1!=NULL){
start=insertEnd(start,l1->val);
l1=l1->next;
}
while(l2!=NULL){
start=insertEnd(start,l2->val);
l2=l2->next;
}
return start;
}