题目:
题目链接:
https://leetcode-cn.com/problems/merge-two-sorted-lists/
解题思路:
主要采用递归的方法来实现有序链表的实现。
代码如下:
class Solution {
public:
//题解1:递归法
ListNode* mergeTwoLists_1(ListNode* l1, ListNode* l2)
{
if(!l1||!l2)return (l1?l1:l2);
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;
}
//题解2:迭代法
ListNode* mergeTwoLists(ListNode* l1,ListNode* l2){
ListNode *dummy=new ListNode(-1);
ListNode *cur=dummy;
while(l1&&l2){
if(l1->val<l2->val){
cur->next=l1;
cur=cur->next;
l1=l1->next;
}
else{
cur->next=l2;
cur=cur->next;
l2=l2->next;
}
}
cur->next=l1?l1:l2;
return dummy->next;
}
};