LeetCode——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.
把两个有序链表合并成一个链表,新的链表也是有序的。返回新链表的表头指针。
题目分析:
每次选择剩下的节点中最小的,而最小的一定是链表1或者链表2剩下部分的第一个。
用递归大法~
AC代码:
/**
* 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)//如果链表1已经空了,直接返回链表2,反之同理
return l2;
if(l2==NULL)
return l1;
ListNode *Head;
if(l1->val<=l2->val)//找较小的节点
{
Head=l1;
Head->next=mergeTwoLists(l1->next,l2);
}
else
{
Head=l2;
Head->next=mergeTwoLists(l1,l2->next);
}
return Head;
}
};