1 /**
2 * Definition for singly-linked list.
3 * struct ListNode {
4 * int val;
5 * struct ListNode *next;
6 * };
7 */
8
9
10 struct ListNode* mergeTwoLists(struct ListNode* l1, struct ListNode* l2){
11 struct ListNode *head=(struct ListNode *)malloc(sizeof(struct ListNode)) ,*tail;
12 head->next = NULL;
13 tail = head;
14
15 while(l1 && l2)
16 {
17 if(l1->val<=l2->val){
18 struct ListNode * p = (struct ListNode *)malloc(sizeof(struct ListNode));
19 p->next = NULL;
20 p->val = l1->val;
21 tail->next = p;
22 tail =p;
23 l1 = l1->next;
24 }else{
25 struct ListNode * p = (struct ListNode *)malloc(sizeof(struct ListNode));
26 p->next = NULL;
27 p->val = l2->val;
28 tail->next = p;
29 tail =p;
30 l2 = l2->next;
31 }
32 }
33 if(l1) //如果去掉这2个if如果l1之后还有节点,l2之后无节点,根据执行顺序就会使整个链表无节点,这2个if的作用是,把剩余节点的链表链接在尾部
34 tail->next = l1;
35 if(l2) //
36 tail->next = l2;
37 return head->next;
38 }