【LeetCode 21】合并两个有序链表

题目链接

【题解】


就是归并排序的一趟合并操作。
新建个链表加在上面就好。(用原来的链表的头结点也没问题)
加个头结点会比较好操作一点。
返回的时候返回头结点的next域就行

【代码】

/**
 * 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 *head = (ListNode*)malloc(sizeof(ListNode));
        ListNode *p = head;
        while (l1 && l2){
            if (l1->val<l2->val){
                p->next = l1;
                l1 = l1->next;
            }else {
                p->next = l2;
                l2 = l2->next;
            }
            p = p->next;
        }
        if (l2) l1 = l2;
        while (l1){
            p->next = l1;
            p = p->next;
            l1 = l1->next;
        }
        p->next = NULL;
        return head->next;
    }
};

猜你喜欢

转载自www.cnblogs.com/AWCXV/p/11821341.html