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


不带头结点

/**
 * 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) {
        if(l1 == NULL)
            return l2;
        if(l2 == NULL)
            return l1;
        ListNode *first = NULL;
        if(l1->val < l2->val) {
            first = l1;
            l1 = l1->next;
        } else {
            first = l2;
            l2 = l2->next;
        }
        ListNode *last = first;
        while(l1 && l2) {
            if(l1->val < l2->val) {
                last->next = l1;
                l1 = l1->next;
            } else {
                last->next = l2;
                l2 = l2->next;
            }
            last = last->next;
        }
        if(l1)
            last->next = l1;
        if(l2)
            last->next = l2;
        return first;
        
    }
};

 

 posted on 2018-07-19 22:31  平和之心  阅读(117)  评论(0编辑  收藏  举报