首页 > 代码库 > 【LeetCode】21. Merge Two Sorted Lists

【LeetCode】21. Merge Two Sorted Lists

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.

题意:合并两个已排序的链表

题不难,但是有很多需要注意的细节,直接贴代码

 1 /**
 2  * Definition for singly-linked list.
 3  * struct ListNode {
 4  *     int val;
 5  *     struct ListNode *next;
 6  * };
 7  */
 8 struct ListNode* mergeTwoLists(struct ListNode* l1, struct ListNode* l2) {
 9     struct ListNode *tmp,*p1,*p2;
10     if(l1==NULL){
11         tmp=l1;
12         l1=l2;
13         l2=tmp;
14     }
15     if(l1==NULL)
16         return l1;
17     p1=l1;
18     p2=l2;
19     while(l1!=NULL){
20         if(l2!=NULL&&l1->val<=l2->val){
21             while(l1->next!=NULL&&l1->next->val<=l2->val) 
22                 l1=l1->next;
23             tmp=l2;
24             l2=l2->next;
25             tmp->next=l1->next;
26             l1->next=tmp;
27             l1=l1->next;
28         }
29         else if(l2!=NULL&&l1->val>l2->val){
30             tmp=l1;
31             l1=l2;
32             l2=tmp;
33             p1=l1;
34         }
35         else if(l2==NULL)
36             return p1;
37     }
38     return p1;
39 }

 感觉写的好乱,重新写一遍:

 1 /**
 2  * Definition for singly-linked list.
 3  * struct ListNode {
 4  *     int val;
 5  *     struct ListNode *next;
 6  * };
 7  */
 8 struct ListNode* mergeTwoLists(struct ListNode* l1, struct ListNode* l2) {
 9     struct ListNode *tmp,*p1;
10     if(l1==NULL&&l2==NULL)
11         return NULL;
12     if(l1==NULL)
13         return l2;
14     if(l2==NULL)
15         return l1;
16     if(l1->val>l2->val){
17         tmp=l1;
18         l1=l2;
19         l2=tmp;
20     }
21     p1=l1;
22     while(l1!=NULL){
23         if(l2!=NULL&&l1->val<=l2->val){
24             while(l1->next!=NULL&&l1->next->val<=l2->val) 
25                 l1=l1->next;
26             tmp=l2;
27             l2=l2->next;
28             tmp->next=l1->next;
29             l1->next=tmp;
30         }
31         else if(l2==NULL)
32             return p1;
33     }
34     return p1;
35 }

 

【LeetCode】21. Merge Two Sorted Lists