作者smart0eddie (smart0eddie)
看板Marginalman
標題Re: [閒聊] 每日leetcode
時間Thu Jul 4 13:55:14 2024
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;
}
};
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 73.173.211.221 (美國)
※ 文章網址: https://www.ptt.cc/bbs/Marginalman/M.1720072516.A.E2B.html
推 DJYOMIYAHINA: 大師 07/04 13:58
→ yam276: 靠北 tree 沙勒我 07/04 14:01
→ yam276: Rust就這了 07/04 14:02