第六周算法分析与设计Ⅱ:Merge Two Sorted Lists

来源:互联网 发布:linux 杀dhcp进程 编辑:程序博客网 时间:2024/05/29 17:08

问题描述:

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.

题目来自于此处

(注:此题难度虽为easy,但感觉挺典型,很有代表性)

解决方案1(非递归):
另起一个结点作为头结点,同时也作为虚拟结点(所谓的dummy node),这样可以方便后续处理的统一。当 l1>vall2>val 时,当前结点的next指向 l2 , l2 则指向下一个;反之指向 l1,同时对 l1 做同样的处理。直到 l1 或者 l2 任一为空,把当前结点的尾部指向非空的那个。

ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {        if(!l1||!l2) return ((l1==l2)?l1:(l1)?l1:l2); //判空的条件。。可能写的有点复杂        ListNode* new_head = new ListNode(1); //不知道还有啥初始化的方法        ListNode* cur_head = new_head;        while(l1&&l2){            if(l1->val<=l2->val){                cur_head->next = l1;                l1 = l1->next;            }            else{                cur_head->next = l2;                l2 = l2->next;            }            cur_head = cur_head->next;        }        cur_head->next = (l1==NULL)?l2:l1;        return new_head->next;    }

时间复杂度O(n),空间复杂度O(1)

解决方案2(递归):
递归的方法与非递归的类似,考虑初始条件及递归过程,当 l1>vall2>val 时,那么将 l1->next 作为新的 l1 进栈;否则 l2->next 进栈;每次递归新的函数时都以 ”l1“ 为新的当前链表的结点。

ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {       if(!l1||!l2) return ((l1==l2)?l1:(l1)?l1:l2);         if(l1->val>=l2->val){            l2->next = mergeTwoLists(l1,l2->next);            return l2;        }        else{            l1->next = mergeTwoLists(l1->next,l2);            return l1;        }    }

空间复杂度为O(n),时间上的话应该是O(1)

有大神说写了程序不分析复杂度的是瓜皮。。

0 0