litcode 合并两个排序链表 递归求解

来源:互联网 发布:sql注入测试工具汇总 编辑:程序博客网 时间:2024/06/09 05:19

将两个排序链表合并为一个新的排序链表

给出 1->3->8->11->15->null2->null, 返回 1->2->3->8->11->15->null


其中链表定义如下:

class ListNode {  public:      int val;      ListNode *next;      ListNode(int val) {          this->val = val;          this->next = NULL;      } };

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    }};


实际上这一道非常简单的题目,不过如果不适用递归的话,可能会比较繁琐,所以这里使用递归的方法求解。


首先分析题目,假定有两个链表头指针   l1,l2;

比较l1->val和l2->val,假定l1较大取出l1->val放到已排好的链表中。继续比较l1->next和l2;

可以看到此时已经存在递归调用的mergeLists(l1->next,l2).

那么递归结束的条件是什么?

就是l1,l2为空,此时返回另外一个即可。

代码如下

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

0 0
原创粉丝点击