Re: [闲聊] 每日leetcode

楼主: sustainer123 (caster)   2024-07-04 09:31:49
https://leetcode.com/problems/merge-nodes-in-between-zeros
2181. Merge Nodes in Between Zeros
给定一linked list head 请合并0-0之间的节点 此节点的值为合并节点之总和
修改后的linked list不可包含0
Example 1:
Input: head = [0,3,1,0,4,5,2,0]
Output: [4,11]
Explanation:
The above figure represents the given linked list. The modified list contains
- The sum of the nodes marked in green: 3 + 1 = 4.
- The sum of the nodes marked in red: 4 + 5 + 2 = 11.
Example 2:
Input: head = [0,1,0,3,0,2,2,0]
Output: [1,3,4]
Explanation:
The above figure represents the given linked list. The modified list contains
- The sum of the nodes marked in green: 1 = 1.
- The sum of the nodes marked in red: 3 = 3.
- The sum of the nodes marked in yellow: 2 + 2 = 4.
Constraints:
The number of nodes in the list is in the range [3, 2 * 105].
0 <= Node.val <= 1000
There are no two consecutive nodes with Node.val == 0.
The beginning and end of the linked list have Node.val == 0.
思路:
虾鸡巴写 我几百年没碰linked list 对啊
大概就遇到0 创新node 没有就加总
Python Code:
class Solution:
def mergeNodes(self, head: Optional[ListNode]) -> Optional[ListNode]:
total = 0
result = ListNode()
tmp = result
head = head.next
while head:
if head.val == 0:
tmp.next = ListNode(total)
tmp = tmp.next
total = 0
else:
total += head.val
head = head.next
return result.next
作者: Furina (芙宁娜)   2024-07-04 09:32:00
大师
作者: DJYOMIYAHINA (通通打死)   2024-07-04 10:25:00
大师

Links booklink

Contact Us: admin [ a t ] ucptt.com