Doing something you intrinsically are enthusiastic with.

2016年8月22日 星期一

Leetcode- Merge two sorted list

清晨7:02 Posted by Unknown No comments

Merge two sorted linked lists and return it as a new list.
 The new list should be made by splicing together the nodes of the first two lists.

Solution: Make a temp node to point to the head pointer of result. 
Then we put each element into the list and return the head of the pointer at last.
class Solution {
public:
    
    ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
        ListNode *dummy = new ListNode(0);
        ListNode *tmp = dummy;
        while (l1 != NULL && l2 != NULL) {
            if (l1->val < l2->val) {
                tmp->next = l1;
                l1 = l1->next;
            } else {
                tmp->next = l2;
                l2 = l2->next;
            }
            tmp = tmp->next;
        }
        if (l1 != NULL) tmp->next = l1;
        else tmp->next = l2;
        return dummy->next;
    }
};

0 意見:

張貼留言