21. Merge Two Sorted Lists(第七周)

来源:互联网 发布:阿里云弹性ip 编辑:程序博客网 时间:2024/06/05 10:50

本题也是递归算法的应用,将两个链表的头部进行比较,将较小的放进新创建的temp链表中,然后将后一个链表头部与另一个链表头部进行比较,不断进行下去,直到有一个链表元素个数为空。 

/**

 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution
{
public:
    ListNode* mergeTwoLists(ListNode* l1, ListNode* l2)
{
        if(l1 == NULL) return l2;
if(l2 == NULL) return l1;
if(l1->val > l2->val)
{
ListNode *temp = l2;
temp->next = mergeTwoLists(l1, l2->next);
return temp;
}
else
{
ListNode *temp = l1;
            temp->next = mergeTwoLists(l1->next, l2);
            return temp;
}
    }
};
0 0