当前位置:网站首页>LeetCode Algorithm 2181. Merge nodes between zero

LeetCode Algorithm 2181. Merge nodes between zero

2022-07-06 07:06:00 Alex_ 12 hours a day 6 days a week

Topic link :2181. Merge nodes between zeros

Ideas

Algorithm : iteration
data structure : Linked list
Ideas : In fact, you can create a new linked list res, And then through head Traverse the original list , encounter 0 Create a new node and mount it to res Tail of , Until we meet the next one 0 node , Otherwise, just let res The tail node value of plus the node currently being traversed .

Code

C++

class Solution {
    
public:
    ListNode* mergeNodes(ListNode* head) {
    
        ListNode *dummyHead = new ListNode(0);
        ListNode *cur = dummyHead;
        while (head->next != nullptr) {
    
            if (head->val == 0) {
    
                ListNode *node = new ListNode(0);
                cur->next = node;
                cur = node;
            }
            cur->val += head->val;
            head = head->next;
        }
        return dummyHead->next;
    }
};
原网站

版权声明
本文为[Alex_ 12 hours a day 6 days a week]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/187/202207060650235505.html