2181. 合并零之间的节点

2181. 合并零之间的节点


题目链接:2181. 合并零之间的节点

代码如下:

cpp 复制代码
/**
 * 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* mergeNodes(ListNode* head) 
    {
       ListNode* Head=new ListNode();  
       ListNode* p=Head;

       while(head!=nullptr)
       {
            if(head->val==0)
            {
                head=head->next;
                int sum=0;
                while(head&&head->val!=0)
                {
                    sum+=head->val;
                    head=head->next;
                }
                if(sum==0)
                {
                    continue;
                }
                ListNode* node=new ListNode(sum);
                p->next=node;
                p=node;
            }
       }
       return Head->next;
    }
};
相关推荐
为啥不吃肉捏7 分钟前
C++/Qt 集成 AutoHotkey
开发语言·c++·qt
努力学习的小廉10 分钟前
【C++】—— string模拟实现
开发语言·c++
小灰灰爱代码30 分钟前
C++——求3*3矩阵主对角元素之和。
c++·算法·矩阵
hjxxlsx1 小时前
插入与冒泡排序(C++)
c++·算法·排序算法
木向1 小时前
leetcode第十二题:整数转罗马数字
c++·算法·leetcode·职场和发展
繁星璀璨G1 小时前
C++11标准模板(STL)- 常用数学函数 - 计算e的给定幂 (ex)(std::exp, std::expf, std::expl)
开发语言·c++·算法·stl·计算e的给定幂
the sun341 小时前
C++红黑树
c++
程序猿练习生1 小时前
C++速通LeetCode中等第20题-随机链表的复制(三步简单图解)
c++·leetcode·链表
阑梦清川2 小时前
C++初阶-list用法总结
开发语言·c++·stl·list
秋落风声2 小时前
C++---类与对象一
c++