Friday, July 3, 2015

Leetcode 21: merge two sorted list

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.

归并两个sorted的链表, 对于这种链表归并,因为可能head的节点会改变,可以引入dummy head来作为整个链表的统一的head节点。 使用cur指针来指向结果链表中的当前tail节点,并且cur->next始终指向下一个加入结果链表中的节点。 

 class Solution {
public:
    ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
        ListNode* dummy = new ListNode(0);
        dummy->next = l1;
        ListNode* cur = dummy;
        while (l1 && l2) {
            if (l1->val < l2->val) {
                cur->next = l1;
                cur = l1;
                l1 = l1->next;
            } else {
                cur->next = l2;
                cur = l2;
                l2 = l2->next;
            }
        }
        if (l1) {
            cur->next = l1;
        }
        if (l2) {
            cur->next = l2;
        }
        return dummy->next;
        delete dummy;
    }
  
};

No comments:

Post a Comment