论坛首页 入门技术论坛

[LeetCode] Merge Two Sorted Lists

浏览 1141 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2013-05-12  

刷题,练习手感!

 

/**
 * 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;
        }
    }
};

 

论坛首页 入门技术版

跳转论坛:
Global site tag (gtag.js) - Google Analytics