Little-Prince

导航

21. 合并两个有序链表

21. 合并两个有序链表

难度简单1172将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
 
示例:
输入:1->2->4, 1->3->4
输出:1->1->2->3->4->4
 
 
代码:
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
        ListNode *mirror,*pre;
        mirror = new ListNode;
        pre = mirror;
        while(l1&&l2)
        {
            if(l1->val<l2->val)
            {
                pre->next = l1;//1->1
                l1 = l1->next;//p1 = 2
            }
            else
            {
                pre->next = l2;//0->1
                l2 = l2->next;//p2 = 3
            }
            pre = pre->next;//pre = 1
        }
        pre->next = l1 == NULL ? l2 : l1;
        return mirror->next;
        delete(mirror);
        
    }
};

 

posted on 2020-07-27 22:23  Little-Prince  阅读(103)  评论(0)    收藏  举报