`
cozilla
  • 浏览: 92109 次
  • 性别: Icon_minigender_1
  • 来自: 南京
社区版块
存档分类
最新评论

[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;
    }
};

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics