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) {
        ListNode dummy(-1);
        ListNode *cur = &dummy;
        
        while(l1 != nullptr && l2 != nullptr)
        {
            if(l1->val < l2->val)
            {
                cur->next = new ListNode(l1->val);
                l1 = l1->next;
            }
            else
            {
                cur->next = new ListNode(l2->val);
                l2 = l2->next;
            }
            
            cur = cur->next;
        }
        
     //one more easy way
//cur->next = (l1 == nullptr) ? l2:l1;
for(; l1 != nullptr; l1 = l1->next, cur = cur->next) cur->next = new ListNode(l1->val); for(; l2 != nullptr; l2 = l2->next, cur = cur->next) cur->next = new ListNode(l2->val); cur->next = nullptr; return dummy.next; } };

 

posted @ 2017-03-28 19:07  chengcy  Views(108)  Comments(0)    收藏  举报