Skip to content

Commit 39bd5bb

Browse files
committedJan 4, 2019
--update: find middle node of linked list
1 parent 20d5b5c commit 39bd5bb

File tree

2 files changed

+52
-0
lines changed

2 files changed

+52
-0
lines changed
 
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
function getMiddleNode(linkedList) {
2+
let slow = linkedList.getFirst();
3+
let fast = linkedList.getFirst();
4+
5+
if (!slow) {
6+
return null;
7+
}
8+
9+
while (fast.next && fast.next.next) {
10+
slow = slow.next;
11+
fast = fast.next.next;
12+
}
13+
14+
return slow;
15+
}
16+
17+
module.exports = {
18+
getMiddleNode,
19+
};
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
const { LinkedList } = require('../index');
2+
const { getMiddleNode } = require('.');
3+
4+
describe('Find the middle node of a LinkedList', () => {
5+
let list = null;
6+
beforeEach(() => {
7+
list = new LinkedList();
8+
list.addAtBeginning('Hello');
9+
list.addAtEnd('World!');
10+
list.addAtEnd('Welcome');
11+
list.addAtEnd('to');
12+
list.addAtEnd('the');
13+
list.addAtEnd('world');
14+
list.addAtEnd('of');
15+
list.addAtEnd('JavaScript');
16+
});
17+
18+
it('Should return `null` for empty list', () => {
19+
list.delete();
20+
expect(getMiddleNode(list)).toEqual(null);
21+
});
22+
23+
it('Should return `to` for the given list', () => {
24+
expect(getMiddleNode(list).data).toEqual('to');
25+
});
26+
27+
it('Should return `Welcome` after deleting 3 last nodes of the list', () => {
28+
list.removeFromEnd();
29+
list.removeFromEnd();
30+
list.removeFromEnd();
31+
expect(getMiddleNode(list).data).toEqual('Welcome');
32+
});
33+
});

0 commit comments

Comments
 (0)