0
点赞
收藏
分享

微信扫一扫

剑指 Offer 25. 合并两个排序的链表

胡桑_b06e 2022-01-31 阅读 63

思路:和归并排序一样就行了

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

 

举报

相关推荐

0 条评论