LeetCode21 Merge Two Sorted Lists

问题描述:
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.

Example:

Input: 1->2->4, 1->3->4
Output: 1->1->2->3->4->4
题源:here;完整代码:here
思路:
依次比较两个list中的第一个;将较小的一个加到返回的list后面。
注意:
在函数中我申请的result并没有用new,而是直接初始化。这样函数结束时就可以回收result的这块内存,如果用new的话需要手动回收一遍,否则会造成内存泄漏。

        ListNode result(0), *curr;
        curr = &result;

        while (l1 && l2){
            if (l1->val <= l2->val){
                curr->next = l1;
                curr = curr->next;
                l1 = l1->next;
            }
            else{
                curr->next = l2;
                curr = curr->next;
                l2 = l2->next;
            }
        }

        curr->next = l1 ? l1 : l2;

        return result.next;

猜你喜欢

转载自blog.csdn.net/m0_37518259/article/details/80710939
今日推荐