leetcode--Merge Two Sorted Lists

来源:互联网 发布:淘宝季康是谁 编辑:程序博客网 时间:2024/06/10 20:52

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.


默认顺序是从小到大。。

代码太丑了。。

/** * 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* result=NULL;        if(l1==NULL && l2==NULL)return result;        else if(l1==NULL)return l2;        else if(l2==NULL)return l1;                if(l1->val>l2->val){result=l2;l2=l2->next;}        else {result=l1;l1=l1->next;}        ListNode* now=result;        while(l1!=NULL && l2!=NULL)        {            if(l1->val>l2->val){now->next=l2;now=now->next;l2=l2->next;}            else{now->next=l1;now=now->next;l1=l1->next;}                                        }        if(l1==NULL &&l2==NULL)        {return result;}        else if(l1==NULL)        {            now->next=l2;        }        else now->next=l1;                return result;            }            };





一种递归的方法。



<span style="font-family: Arial, Helvetica, sans-serif;">class Solution {</span>
public:    ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) {        if(l1 == NULL) return l2;        if(l2 == NULL) return l1;        if(l1->val < l2->val) {            l1->next = mergeTwoLists(l1->next, l2);            return l1;        } else {            l2->next = mergeTwoLists(l2->next, l1);            return l2;        }    }};



0 0