21. Merge Two Sorted Lists

来源:互联网 发布:重庆数据恢复发 编辑:程序博客网 时间:2024/06/05 17:01

题目:

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.

代码如下:

class Solution {public:    ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {        if (l1 == NULL) return l2;        if (l2 == NULL) return l1;        if (l1->val < l2->val) {          l1->next = mergeTwoLists(l1->next, l2);          return l1;        }        else {          l2->next = mergeTwoLists(l1, l2->next);          return l2;        }    }};

解体思路:

本题利用递归的思路。将两个链表归并排序,即对比两个链表返回较小值,可以分解为多个比较两个值大小的子问题。继续这个操作,即可得出答案。

原创粉丝点击