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、递归版本
/**
* 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) {
l1->next = mergeTwoLists(l1->next, l2);
return l1;
}
else {
l2->next = mergeTwoLists(l2->next, l2);
return l2;
}
}
};
2、非递归
/**
* 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;
ListNode *temphead = NULL;
ListNode *l1pointer = l1;
ListNode *l2pointer = l2;
ListNode *temptail = NULL;
//新建一个链表,头节点指向l1,l2中值较小的节点,尾节点指向头节点
if (l1->val < l2->val) {
temphead = l1;
l1pointer = l1pointer->next;
}
else {
temphead = l2;
l2pointer = l2pointer->next;
}
temptail = temphead;
while (l1pointer != NULL && l2pointer != NULL) {
//将l1,l2中值小的数依次接到新链表上
if (l1pointer->val < l2pointer->val){
temptail->next = l1pointer;
l1pointer = l1pointer->next;
}
else {
temptail->next = l2pointer;
l2pointer = l2pointer->next;
}
temptail = temptail->next;
}
if (l1pointer == NULL)
temptail->next = l2pointer;
else
temptail->next = l1pointer;
return temphead;
}
};
递归方法开销大,当链表过长时,会发生溢出,推荐非递归方法
本文介绍了一种合并两个已排序的单链表的方法,并提供了递归和非递归两种实现方式。递归方法简洁但可能因链表过长导致溢出;非递归方法稳定可靠,适用于实际应用。

1036

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



