Skip to content

Commit

Permalink
move to medium
Browse files Browse the repository at this point in the history
  • Loading branch information
imteekay committed Mar 4, 2022
1 parent 6cd64e9 commit afe6cc8
Show file tree
Hide file tree
Showing 2 changed files with 67 additions and 0 deletions.
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;
}
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);
});
});

0 comments on commit afe6cc8

Please sign in to comment.