Merge Two Sorted Lists

非常简洁的代码,初始变量以及边界条件的定义一直让我很烦躁。期待能找到最简洁方式的途径

class Solution {
public:
    ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        ListNode* head = NULL;
        ListNode** cur = &head;
        while (l1 && l2) {
            if (l1->val <= l2->val) {
                *cur = l1;
                l1 = l1->next;
            } else {
                *cur = l2;
                l2 = l2->next;
            }
            cur = &((*cur)->next);
        }
        if (!l1) *cur = l2;
        if (!l2) *cur = l1;
        return head;
    }
};

 

posted @ 2013-06-13 15:20  dmthinker  阅读(113)  评论(0)    收藏  举报