-
-
Notifications
You must be signed in to change notification settings - Fork 81
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
2 changed files
with
67 additions
and
0 deletions.
There are no files selected for viewing
37 changes: 37 additions & 0 deletions
37
...g_interviews/leetcode/medium/merge-nodes-in-between-zeros/merge-nodes-in-between-zeros.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,37 @@ | ||
export class ListNode { | ||
constructor(val, next) { | ||
this.val = val === undefined ? 0 : val; | ||
this.next = next === undefined ? null : next; | ||
} | ||
} | ||
|
||
export function mergeNodes(head) { | ||
let nonZeroHead; | ||
let node; | ||
let nextNode; | ||
let currentNode = head.next; | ||
let valueSum = 0; | ||
let gotFirstNode = false; | ||
|
||
while (currentNode) { | ||
valueSum += currentNode.val; | ||
|
||
if (currentNode.val === 0) { | ||
nextNode = new ListNode(valueSum); | ||
valueSum = 0; | ||
|
||
if (gotFirstNode) { | ||
node.next = nextNode; | ||
node = node.next; | ||
} else { | ||
node = nextNode; | ||
nonZeroHead = nextNode; | ||
gotFirstNode = true; | ||
} | ||
} | ||
|
||
currentNode = currentNode.next; | ||
} | ||
|
||
return nonZeroHead; | ||
} |
30 changes: 30 additions & 0 deletions
30
...s/leetcode/medium/merge-nodes-in-between-zeros/tests/merge-nodes-in-between-zeros.test.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,30 @@ | ||
import { describe, it, expect } from 'vitest'; | ||
import { ListNode, mergeNodes } from '../merge-nodes-in-between-zeros'; | ||
|
||
function buildList(nums, initValue = 0) { | ||
let head = new ListNode(initValue); | ||
let node = head; | ||
let nextNode; | ||
|
||
for (let i = 1; i < nums.length; i++) { | ||
nextNode = new ListNode(nums[i]); | ||
node.next = nextNode; | ||
node = node.next; | ||
} | ||
|
||
return head; | ||
} | ||
|
||
describe('mergeNodes', () => { | ||
it('removes zeros and merges nodes', () => { | ||
const head = buildList([0, 3, 1, 0, 4, 5, 2, 0]); | ||
const result = buildList([4, 11], 4); | ||
expect(mergeNodes(head)).toEqual(result); | ||
}); | ||
|
||
it('removes zeros and merges nodes', () => { | ||
const head = buildList([0, 1, 0, 3, 0, 2, 2, 0]); | ||
const result = buildList([1, 3, 4], 1); | ||
expect(mergeNodes(head)).toEqual(result); | ||
}); | ||
}); |