题解 | #合并两群能量值#
合并两群能量值
https://www.nowcoder.com/practice/d728938f66ac44b5923d4f2e185667ec
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) : val(x), next(nullptr) {}
* };
*/
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param l1 ListNode类
* @param l2 ListNode类
* @return ListNode类
*/
ListNode* mergeEnergyValues(ListNode* list1, ListNode* list2) {
// write code here
ListNode* dummy = new ListNode(-1);
ListNode* list3 = dummy;
while (list1 && list2) {
if (list1->val > list2->val) {
list3->next = list1;
list1 = list1->next;
} else {
list3->next = list2;
list2 = list2->next;
}
list3 = list3->next;
}
if (list1)
list3->next = list1;
if (list2)
list3->next = list2;
return dummy->next;
}
};
方法二:递归
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) : val(x), next(nullptr) {}
* };
*/
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param l1 ListNode类
* @param l2 ListNode类
* @return ListNode类
*/
ListNode* mergeEnergyValues(ListNode* l1, ListNode* l2) {
// write code here
if (l1 == NULL) {
return l2;
}
if (l2 == NULL) {
return l1;
}
if (l1->val >= l2->val) {
l1->next = mergeEnergyValues(l1->next, l2);
return l1;
}
l2->next = mergeEnergyValues(l1, l2->next);
return l2;
}
};
一、题目考察的知识点
归并排序
二、题目解答方法的文字分析
典型的归并排序的模板题,就是比较两个链表中的值,一一比较,把大的数放到另一个链表里就行
三、本题解析所用的编程语言
c++
牛客课后习题题解 文章被收录于专栏
等待蜕变

