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.

 

该题是要求合并两个已排序的列表,根据stl库里list的sort,这里的排序是指从小到大排序

那么分三种情况来处理:

对于list l1 和 list l2,可能下一个要添加的元素是要比较两个链表中的元素,找到较小的添加;

也可能是只有l1中的元素可以添加;也可能是只有l2中的元素可以添加;

所以可以写出如下程序

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





原文地址:https://www.cnblogs.com/gremount/p/5771296.html