【LeetCode】21. Merge Two Sorted Lists

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.

 

由于l1,l2是已排序的,因此l1->val,l2->val分别代表了两个链表的最小值。

逐个最小值取出,装入新链表。

当一个链表为空时,另一个链表整个链入。

/**
 * 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* newhead = new ListNode(-1);
        ListNode* tail = newhead;
        while(l1 != NULL && l2 != NULL)
        {
            if(l1->val <= l2->val)
            {
                tail->next = l1;
                l1 = l1->next;
            }
            else
            {
                tail->next = l2;
                l2 = l2->next;
            }
            tail = tail->next;
        }
        if(l1 != NULL)
            tail->next = l1;
        if(l2 != NULL)
            tail->next = l2;
        return newhead->next;
    }
};

你可能感兴趣的:(LeetCode)