题目来源:
leetcode题目,网址: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) {
ListNode* res=new ListNode();//空头;
ListNode* head=res;
while(l1!=NULL && l2!=NULL){
if(l1->val < l2->val){
res->next=l1;
l1=l1->next;
}else{
res->next=l2;
l2=l2->next;
}
res=res->next;
}
if(l1!=NULL){
res->next=l1;
}else{
res->next=l2;
}
return head->next;
}
};
总结:
官方题解给出了递归和迭代两种解法。