题解 | #合并两群能量值#
合并两群能量值
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* l1, ListNode* l2) {
// 创建一个虚拟头节点
ListNode* dummy=new ListNode(-1);
ListNode* cur=dummy;
// 归并排序思想
while (l1 && l2) {
if(l1->val>=l2->val){
cur->next=l1;
l1=l1->next;
}else{
cur->next=l2;
l2=l2->next;
}
cur=cur->next;
}
//连接剩余节点
if(l1) cur->next=l1;
if(l2) cur->next=l2;
return dummy->next;
}
};