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;
}
};

本文介绍如何解决LeetCode上的经典题目“合并两个有序链表”。通过递归方法,将两个有序链表合并为一个新的有序链表,并返回新链表的头节点。此方法简单高效,易于理解和实现。
9万+

被折叠的 条评论
为什么被折叠?



