Skip to content

Commit 024eebb

Browse files
committed
--update: added linked list
1 parent 4a1599b commit 024eebb

File tree

2 files changed

+86
-0
lines changed

2 files changed

+86
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
const { Node, LinkedList } = require('.');
2+
3+
describe('Data Structures: Linked Lists', () => {
4+
describe('Node of a List', () => {
5+
it('Should be a class', () => {
6+
expect(typeof Node.prototype.constructor).toEqual('function');
7+
});
8+
9+
it('Should set the data and next field of a node', () => {
10+
const node = new Node('Hello', null);
11+
expect(node.data).toEqual('Hello');
12+
expect(node.next).toEqual(null);
13+
});
14+
});
15+
16+
describe('LinkedList Instance', () => {
17+
it('Should be a class', () => {
18+
expect(typeof LinkedList.prototype.constructor).toEqual('function');
19+
});
20+
21+
it('Should set the data and next field of a node', () => {
22+
const list = new LinkedList();
23+
expect(list.head).not.toEqual(undefined);
24+
expect(list.head).toEqual(null);
25+
});
26+
});
27+
28+
describe('LinkedList API', () => {
29+
let list = new LinkedList();
30+
31+
beforeEach(() => {
32+
list = new LinkedList();
33+
});
34+
35+
it('Should add element at beginning using list.addAtBeginning()', () => {
36+
list.addAtBeginning(12);
37+
expect(list.head.data).toEqual(12);
38+
39+
list.addAtBeginning(15);
40+
expect(list.head.data).toEqual(15);
41+
});
42+
43+
it('Should return the present size of the list using list.length()', () => {
44+
expect(list.length()).toEqual(0);
45+
list.addAtBeginning(1);
46+
list.addAtBeginning(2);
47+
list.addAtBeginning(3);
48+
expect(list.length()).toEqual(3);
49+
});
50+
});
51+
});
+35
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
class Node {
2+
constructor(data, next) {
3+
this.data = data;
4+
this.next = next;
5+
}
6+
}
7+
8+
class LinkedList {
9+
constructor() {
10+
this.head = null;
11+
}
12+
13+
addAtBeginning(element) {
14+
const node = new Node(element, null);
15+
16+
if (!this.head) {
17+
this.head = node;
18+
} else {
19+
node.next = this.head;
20+
this.head = node;
21+
}
22+
}
23+
24+
length() {
25+
let address = this.head;
26+
let count = 0;
27+
while (address) {
28+
count += 1;
29+
address = address.next;
30+
}
31+
return count;
32+
}
33+
}
34+
35+
module.exports = { LinkedList, Node };

0 commit comments

Comments
 (0)