s4553711
4/1/2017 - 4:22 PM

leetcode-21. Pay attention to the h and t linked list pointer

leetcode-21. Pay attention to the h and t linked list pointer

/**
 * 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 *h1 = new ListNode(0);
        ListNode *h2 = new ListNode(0);
        h1->next = l1;
        h2->next = l2;
        
        ListNode *h = new ListNode(0);
        ListNode *t = h;
        
        while (h1->next != NULL || h2->next != NULL) {
            if (h1->next == NULL || 
                h2->next != NULL && h1->next->val > h2->next->val) {
                    t->next = h2->next;
                    t = t->next;
                    h2->next = t->next;
            } else {
                t->next = h1->next;
                t = t->next;
                h1->next = t->next;
            }
        }
        return h->next;
    }
};