LeetCode #21 – Merge Two Sorted Lists

链接:https://leetcode.com/problems/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.

题意:给定两个有序链表,合并成新的有序链表,返回新链表首节点。

分析:开一个新链表,从小到大加进去就可以了,注意判断结尾NULL

CPP代码:

class Solution {
public:
    ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
        ListNode * head = new ListNode(0);
        ListNode * p = head;
        while(l1 != NULL || l2 != NULL) {
            if(l1 == NULL || (l2 != NULL && l2->val < l1->val)) {
                p->next = new ListNode(l2->val);
                l2 = l2->next;
            }
            else {
                p->next = new ListNode(l1->val);
                l1 = l1->next;
            }
            p = p->next;
        }
        return head->next;
    }
};

欢迎留言