LeetCode 21. Merge Two Sorted Lists

Posted Travelller

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode 21. Merge Two Sorted Lists相关的知识,希望对你有一定的参考价值。

链表并归排序

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

别人的:

①设一个preHead,return preHead->next;

②直接复制地址,无需开辟新空间。

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

 

以上是关于LeetCode 21. Merge Two Sorted Lists的主要内容,如果未能解决你的问题,请参考以下文章

Leetcode---21. Merge Two Sorted Lists

Leetcode 21. Merge Two Sorted Lists

LeetCode 21. Merge Two Sorted Lists

LeetCode算法-21Merge Two Sorted Lists

Leetcode 21. Merge Two Sorted Lists

[LeetCode] 21. Merge Two Sorted Lists