天天看點

LeetCode::Merge Two Sorted Lists

https://oj.leetcode.com/problems/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.

/**
 * 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 *aCur = l1;
        ListNode *bCur = l2;

        ListNode *newHead = NULL;
 
        if (aCur->val < bCur->val) {
            newHead = aCur;
            aCur = aCur->next;
        } else {
            newHead = bCur;
            bCur = bCur->next;
        }

        ListNode *newCur = newHead;

        while (aCur != NULL && bCur != NULL) {
            if (aCur->val < bCur->val) {
                newCur->next = aCur;
                aCur = aCur->next;
            } else {
                newCur->next = bCur;
                bCur = bCur->next;
            }
            newCur = newCur->next;
        }

        if (aCur != NULL) {
            newCur->next = aCur;
        } else if (bCur != NULL) {
            newCur->next = bCur;
        }

        return newHead;
    }
};