题目描述:
将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
学习记录:
数据结构上学过的想法,直接定abc三个指针移动,不用开辟新的空间,一遍过
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* mergeTwoLists(ListNode* list1, ListNode* list2) {
if(list1==nullptr) return list2;
if(list2==nullptr) return list1;
ListNode* list_result=nullptr;
ListNode* a;ListNode* b;
if(list1->val < list2->val)
{
list_result=list1;
a=list1->next;
b=list2;
}
else
{
list_result=list2;
b=list2->next;
a=list1;
}
ListNode* c=list_result;
while(a!=nullptr && b!=nullptr)
{
if( a->val < b->val )
{
c->next=a;
c=c->next;
a=a->next;
}
else
{
c->next=b;
c=c->next;
b=b->next;
}
}
if(a!=nullptr) c->next=a;
if(b!=nullptr) c->next=b;
return list_result;
}
};
答案使用的递归的方法,也是非常巧妙的
class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
if (l1 == null) {
return l2;
} else if (l2 == null) {
return l1;
} else if (l1.val < l2.val) {
l1.next = mergeTwoLists(l1.next, l2);
return l1;
} else {
l2.next = mergeTwoLists(l1, l2.next);
return l2;
}
}
}
作者:LeetCode-Solution
链接:https://leetcode.cn/problems/merge-two-sorted-lists/solution/he-bing-liang-ge-you-xu-lian-biao-by-leetcode-solu/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。