leetcode-21.合併兩個有序鏈表

#include<iostream>
using namespace std;
struct ListNode {
  int val;
  ListNode *next;
  ListNode(int x) : val(x), next(NULL) {}
};

ListNode* mergeTwoLists(ListNode* l1, ListNode* l2);
int main(){
    //sort->asc
    ListNode *l1 = new ListNode(1);
    ListNode *l2 = new ListNode(6);
    ListNode *l3 = new ListNode(7);
    l1->next = l2;
    l2->next = l3;

    ListNode *ll1 = new ListNode(1);
    ListNode *ll2 = new ListNode(2);
    ListNode *ll3 = new ListNode(4);
    ll1->next = ll2;
    ll2->next = ll3;
    ListNode *l = mergeTwoLists(l1,ll1);
    while(l){
        cout<<l->val<<endl;
        l = l->next;
    }

    return 0;
}
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {

    if(!l1)
        return l2;
    else if(!l2)
        return l1;
    else if(l1->val < l2->val){
        l1->next = mergeTwoLists(l1->next,l2);
        return l1;
    }else{
        l2->next = mergeTwoLists(l2->next,l1);
        return l2;
    }

}
1
1
2
4
6
7

Process returned 0 (0x0)   execution time : 0.002 s
Press ENTER to continue.

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章