Re: [闲聊] 每日leetcode

楼主: smart0eddie (smart0eddie)   2024-07-04 13:55:14
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;
}
};
作者: DJYOMIYAHINA (通通打死)   2024-07-04 13:58:00
大师
作者: yam276 ('_')   2024-07-04 14:01:00
靠北 tree 沙勒我Rust就这了

Links booklink

Contact Us: admin [ a t ] ucptt.com