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

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

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

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