Leetcode#21 Merge Two Sorted Lists

原题地址

链表归并排序的一个小函数

代码:

 1 ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) {
 2         ListNode *h = NULL;
 3         ListNode *t = NULL;
 4         
 5         while (l1 && l2) {
 6             ListNode *n = NULL;
 7             if (l1->val <= l2->val) {
 8                 n = l1;
 9                 l1 = l1->next;
10             }
11             else {
12                 n = l2;
13                 l2 = l2->next;
14             }
15             if (!h)
16                 h = t = n;
17             else {
18                 t->next = n;
19                 t = t->next;
20             }
21         }
22         
23         while (l1) {
24             if (!h)
25                 h = t = l1;
26             else {
27                 t->next = l1;
28                 t = t->next;
29             }
30             l1 = l1->next;
31         }
32         
33         while (l2) {
34             if (!h)
35                 h = t = l2;
36             else {
37                 t->next = l2;
38                 t = t->next;
39             }
40             l2 = l2->next;
41         }
42         
43         return h;
44 }
原文地址:https://www.cnblogs.com/boring09/p/4266829.html