[LeetCode] Merge Two Sorted 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* head, *cur, *tmp;
        head = getNext(l1, l2);
        cur = head;
        while (true) {
            if (l1 == NULL || l2 == NULL) break;
            cur->next = getNext(l1, l2);
            cur = cur->next;
        }
        if (l1 != NULL) cur->next = l1;
        if (l2 != NULL) cur->next = l2;
        return head;
    }
    
    ListNode* getNext(ListNode*& l1, ListNode*&l2) {
        if (l1->val > l2->val) {
            ListNode* t = l2;
            l2 = l2->next;
            return t;
        } else {
            ListNode* t = l1;
            l1 = l1->next; 
            return t;
        }
    }
};

 

/**
 * 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 || l2 == NULL) return l1 == NULL ? l2 : l1;
        ListNode head(0);
        ListNode *cur = &head;
        while (l1 != NULL && l2 != NULL) {
            if (l1->val < l2->val) {
                cur->next = l1;
                l1 = l1->next;
                cur = cur->next;
            }
            else {
                cur->next= l2;
                l2 = l2->next;
                cur = cur->next;
            }
        }
        if (l1 != NULL) cur->next= l1;
        else if (l2 != NULL) cur->next = l2;
        return head.next;
    }
};

 

你可能感兴趣的:(LeetCode)