2024-07-04
2181. Merge Nodes in Between Zeros
You are given the head of a linked list, which contains a series of integers
separated by 0's. The beginning and end of the linked list will have Node.val
== 0.
For every two consecutive 0's, merge all the nodes lying in between them into
a single node whose value is the sum of all the merged nodes. The modified
list should not contain any 0's.
Return the head of the modified linked list.
題目要求是把兩個 0 之間的 node 數值合併,把 0 丟掉
需要用兩個 pointer
一個紀錄留在 list 上的 node 並且根據當前 node 修改內容
一個沿著 list 往下走
我是想邊走邊處理 搞得有點麻煩
答案是直接掃 0 之間的 node 算總和再直接改會比較快也比較簡單
class Solution {
public:
ListNode* mergeNodes(ListNode* head) {
head = head->next;
ListNode* left = head;
ListNode* cur = head->next;
while (cur) {
left->next = cur->next;
if (0 != cur->val) {
left->val += cur->val;
}
else {
left = cur->next;
cur = cur->next;
}
if (cur) {
cur = cur->next;
}
}
return head;
}
};