美文网首页
21. Merge Two Sorted Lists

21. Merge Two Sorted Lists

作者: SilentDawn | 来源:发表于2018-05-23 13:56 被阅读0次

Problem

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.

Example:

Input: 1->2->4, 1->3->4
Output: 1->1->2->3->4->4

Code

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
static int var = [](){
    std::ios::sync_with_stdio(false);
    cin.tie(NULL);
    return 0;
}();
class Solution {
public:
    ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
        if(l1==NULL && l2==NULL)
            return NULL;
        if(l1!=NULL && l2==NULL)
            return l1;
        if(l1==NULL && l2!=NULL)
            return l2;
        ListNode* header = NULL;
        if(l1->val < l2->val){
            header = l1;
            l1 = l1->next;
        }else{
            header = l2;
            l2 = l2->next;
        };
        ListNode* temp = header;
        while(l1 || l2){
            if(l1==NULL){
                temp->next = l2;
                break;
            }
            if(l2==NULL){
                temp->next = l1;
                break;
            }
            if(l1->val < l2->val){
                temp->next = l1;
                l1 = l1->next;
                temp = temp->next;
                
            }
            else{
                temp->next = l2;
                l2 = l2->next;
                temp = temp->next;     
            }
        }   
        return header;
    }
};

Result

21 Merge Two Sorted Lists.png

相关文章

网友评论

      本文标题:21. Merge Two Sorted Lists

      本文链接:https://www.haomeiwen.com/subject/jxsrjftx.html