[Leetcode]-Merge Two Sorted Lists

来源:互联网 发布:软件开发培训机构 编辑:程序博客网 时间:2024/05/17 00:04

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.
题目:合并两个排序后的单链表,要求合并之后也是排序好的
思路:递归合并
这里写图片描述

/** * Definition for singly-linked list. * struct ListNode { *     int val; *     struct ListNode *next;  * }; */struct ListNode* mergeTwoLists(struct ListNode* l1, struct ListNode* l2) {    if(NULL == l1) return l2;    if(NULL == l2) return l1;    struct ListNode* MergeList = NULL;    if(l1->val < l2->val)    {        MergeList = l1;        MergeList->next = mergeTwoLists(l1->next,l2);    }    else    {        MergeList = l2;        MergeList->next = mergeTwoLists(l1,l2->next);    }    return MergeList;}
1 0
原创粉丝点击