【LeetCode 110】Merge Two Sorted Lists

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.

将两个有序链表合并成一个有序链表。

C++递归解法:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */

Class Solution{

public:

bool mergeTwoLists(ListNode* l1,ListNode* l2)

{

  if(!l1) return l2;

  if(!l2) return l1;

  ListNode *r = NULL;

  if(l1->val<l2->val)

  {

    r = l1;

    return = mergeTwoLists(l1->next,l2);

  }

  if(l1->val>l2->val)

  {

    r = l2;

    return = mergeTwoLists(l1,l2->next);

  }

}

}

关于递归的使用:

1.分而治之的思想,先看问题的最小块,比如本题中最小的单元是两个数的比较,小的那个数加入到新的链表中;

2.递归本身包含了循环,所以不能在循环语句中再加递归;

3.停止条件非常重要;

4.虽然有ListNode* r = NULL,但是递归的运算顺序就是从最后一个单元不停地往前返回值,最终连成一个链表,也就是每次递归都会得到一个r,然后返回给上一个,最终返回最开始的头节点。

posted on 2016-03-18 14:53  不小的文  阅读(108)  评论(0编辑  收藏  举报

导航