LeetCode21:合并两个有序链表

将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。 

 

示例:

输入:1->2->4, 1->3->4
输出:1->1->2->3->4->4

 

很简单的循环判断,但是申请了一个dummyhead的空间。

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

最后一个链表循环完毕后其实可以直接把第二个链表接在后面,不需要再循环了。

 

或者采用递归的方法,需要消耗更多的栈空间。

 1 class Solution {
 2 public:
 3     ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
 4         if (l1 == nullptr) {
 5             return l2;
 6         } else if (l2 == nullptr) {
 7             return l1;
 8         } else if (l1->val < l2->val) {
 9             l1->next = mergeTwoLists(l1->next, l2);
10             return l1;
11         } else {
12             l2->next = mergeTwoLists(l1, l2->next);
13             return l2;
14         }
15     }
16 };
17 
18 作者:LeetCode-Solution
19 链接:https://leetcode-cn.com/problems/merge-two-sorted-lists/solution/he-bing-liang-ge-you-xu-lian-biao-by-leetcode-solu/
20 来源:力扣(LeetCode)
21 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

 

posted @ 2020-06-27 11:00  __rookie  阅读(122)  评论(0编辑  收藏  举报