LCR 142. 训练计划 IV - 力扣(LeetCode)
迭代法
通过循环判断两个链表的值的大小来改变结点的指向,从而达到合并有序链表的目的。
要注意:优先判空。迭代法一定会漏下一个结点,最后需要判断是那条链表漏下了。
/**
* 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* trainningPlan(ListNode* l1, ListNode* l2) {
//判空
if(!l1) return l2;
if(!l2) return l1;
ListNode* head = new ListNode(0);//新建结点作为新链表的头结点
ListNode* it = head; //用于迭代链表的指针
while(l1 && l2){
//判断值的大小,连接结点后移动l1或l2
if(l1->val >= l2->val) {
it->next = l2;
l2 = l2->next;
}
else{
it->next = l1;
l1 = l1->next;
}
it = it->next;
}
//寻找落下的结点
if(l1) it->next = l1;
if(l2) it->next = l2;
return head->next;
}
};
递归法
代码先放这里,有空再说(其实我也不太会)
/**
* 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;
}else if(list2 == nullptr){
return list1;
}else if(list1->val > list2->val){
list2->next = mergeTwoLists(list2->next, list1);
return list2;
}else{
list1->next = mergeTwoLists(list1->next, list2);
return list1;
}
}
};