Skip to content

Commit 0ee9a8d

Browse files
committed
feat: add No.2181
1 parent 3a2f409 commit 0ee9a8d

File tree

1 file changed

+96
-0
lines changed

1 file changed

+96
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,96 @@
1+
# 2181. Merge Nodes in Between Zeros
2+
3+
- Difficulty: Medium.
4+
- Related Topics: Linked List, Simulation.
5+
- Similar Questions: Linked List Components.
6+
7+
## Problem
8+
9+
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`.
10+
11+
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.
12+
13+
Return **the** `head` **of the modified linked list**.
14+
15+
 
16+
Example 1:
17+
18+
![](https://assets.leetcode.com/uploads/2022/02/02/ex1-1.png)
19+
20+
```
21+
Input: head = [0,3,1,0,4,5,2,0]
22+
Output: [4,11]
23+
Explanation:
24+
The above figure represents the given linked list. The modified list contains
25+
- The sum of the nodes marked in green: 3 + 1 = 4.
26+
- The sum of the nodes marked in red: 4 + 5 + 2 = 11.
27+
```
28+
29+
Example 2:
30+
31+
![](https://assets.leetcode.com/uploads/2022/02/02/ex2-1.png)
32+
33+
```
34+
Input: head = [0,1,0,3,0,2,2,0]
35+
Output: [1,3,4]
36+
Explanation:
37+
The above figure represents the given linked list. The modified list contains
38+
- The sum of the nodes marked in green: 1 = 1.
39+
- The sum of the nodes marked in red: 3 = 3.
40+
- The sum of the nodes marked in yellow: 2 + 2 = 4.
41+
```
42+
43+
 
44+
**Constraints:**
45+
46+
47+
48+
- The number of nodes in the list is in the range `[3, 2 * 105]`.
49+
50+
- `0 <= Node.val <= 1000`
51+
52+
- There are **no** two consecutive nodes with `Node.val == 0`.
53+
54+
- The **beginning** and **end** of the linked list have `Node.val == 0`.
55+
56+
57+
58+
## Solution
59+
60+
```javascript
61+
/**
62+
* Definition for singly-linked list.
63+
* function ListNode(val, next) {
64+
* this.val = (val===undefined ? 0 : val)
65+
* this.next = (next===undefined ? null : next)
66+
* }
67+
*/
68+
/**
69+
* @param {ListNode} head
70+
* @return {ListNode}
71+
*/
72+
var mergeNodes = function(head) {
73+
var newHead = new ListNode();
74+
var resNow = newHead;
75+
var now = head;
76+
while (now) {
77+
if (now.val === 0 && now.next) {
78+
resNow.next = new ListNode();
79+
resNow = resNow.next;
80+
} else if (now.val !== 0) {
81+
resNow.val += now.val;
82+
}
83+
now = now.next;
84+
}
85+
return newHead.next;
86+
};
87+
```
88+
89+
**Explain:**
90+
91+
nope.
92+
93+
**Complexity:**
94+
95+
* Time complexity : O(n).
96+
* Space complexity : O(n).

0 commit comments

Comments
 (0)