每日一题——链表合并

来源:互联网 发布:mac的python 编辑:程序博客网 时间:2024/06/06 14:17
递归class Solution {public:    /**     * @param ListNode l1 is the head of the linked list     * @param ListNode l2 is the head of the linked list     * @return: ListNode head of linked list     */    ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) {        // write your code here        if(l1 ==NULL)            return l2;        if(l2 == NULL)            return l1;       ListNode* newList = NULL;       if(l1->val <= l2->val)       {           newList = l1;           newList->next = mergeTwoLists(l1->next,l2);       }       if(l1->val > l2->val)       {           newList = l2;           newList->next = mergeTwoLists(l1,l2->next);       }        return newList;    }};
非递归ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) {        // write your code here        if(l1 ==NULL)            return l2;        if(l2 == NULL)            return l1;        ListNode* newNode = NULL;        if(l1->val <= l2->val)        {            newNode = l1;            l1 = l1->next;        }        else        {            newNode = l2;            l2 = l2->next;        }        ListNode* cur = newNode;        while(l1 && l2)        {            if(l1->val <= l2->val)            {                cur->next = l1;                cur = l1;                l1 = l1->next;            }            else            {                cur->next = l2;                cur = l2;                l2 = l2->next;            }        }        if(l1)            cur->next = l1;        if(l2)            cur->next = l2;        return newNode;    }