[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.
问题:将两个已排序的列表,合并为一个有序列表。
令 head 为两个列表表头中较小的一个,令 p 为新的已排序的最后一个元素。令 l1, l2 分别为两个列表中未排序部分的首节点。依次将 l1, l2 中的较小值追加到 p 后面,并调整 p 和 l1、l2较小者指针即可。
1 ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) { 2 3 if (l1 == NULL) { 4 return l2; 5 } 6 7 if (l2 == NULL) { 8 return l1; 9 } 10 11 ListNode* head = new ListNode(0); 12 if (l1->val <= l2->val) { 13 head = l1; 14 l1 = l1->next; 15 }else{ 16 head = l2; 17 l2 = l2->next; 18 } 19 20 ListNode* p = head; 21 22 while(l1 != NULL && l2 != NULL){ 23 24 if(l1->val <= l2->val){ 25 p->next = l1; 26 p = p->next; 27 l1 = l1->next; 28 }else{ 29 p->next = l2; 30 p = p->next; 31 l2 = l2->next; 32 } 33 } 34 35 if (l1 == NULL) { 36 p->next = l2; 37 } 38 39 if (l2 == NULL) { 40 p->next = l1; 41 } 42 43 return head; 44 }