Skip to content

Commit 800d51b

Browse files
test: write test cases for singly LinkedList class
1 parent a1ff20d commit 800d51b

File tree

2 files changed

+61
-4
lines changed

2 files changed

+61
-4
lines changed

src/linked-list/LinkedList.ts

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -7,18 +7,18 @@ export class Node<T> implements INode<T> {
77
public data: T;
88
public next?: INode<T>;
99

10-
constructor(data: T) {
10+
constructor(data?: T) {
1111
this.data = data;
1212
this.next = null;
1313
}
1414
}
1515

1616
export class LinkedList<T> {
17-
private head: INode<T> | null;
18-
protected tail: INode<T> | null;
17+
public head: INode<T> | null;
18+
public tail: INode<T> | null;
1919
protected length: number;
2020

21-
constructor(data: T) {
21+
constructor(data?: T) {
2222
this.head = new Node(data);
2323
this.tail = this.head;
2424
this.length = 1;
Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
import { LinkedList, Node } from '../LinkedList';
2+
3+
describe('Singly Linked List', () => {
4+
test('create empty list node', () => {
5+
const node = new Node();
6+
7+
expect(node.data).toBeUndefined();
8+
expect(node.next).toBeNull();
9+
});
10+
11+
test('create list node with value', () => {
12+
const node = new Node(10);
13+
14+
expect(node.data).toBe(10);
15+
expect(node.next).toBeNull();
16+
});
17+
18+
test('create list node with object as a value', () => {
19+
const nodeValue = { key: 1, value: 'test' };
20+
const node = new Node(nodeValue);
21+
22+
expect(node.data.key).toBe(1);
23+
expect(node.data.value).toBe('test');
24+
expect(node.next).toBeNull();
25+
});
26+
27+
test('append node to linked list', () => {
28+
const linkedList = new LinkedList();
29+
30+
linkedList.append(5);
31+
32+
expect(linkedList.head.data).toBeUndefined();
33+
expect(linkedList.head.next.data).toBe(5);
34+
expect(linkedList.head.next.next).toBeNull();
35+
});
36+
37+
test('prepend node to linked list', () => {
38+
const linkedList = new LinkedList();
39+
40+
linkedList.prepend(5);
41+
42+
expect(linkedList.head.data).toBe(5);
43+
expect(linkedList.tail.next).toBeNull();
44+
});
45+
46+
test('insert node list in a given index', () => {
47+
const linkedList = new LinkedList();
48+
49+
const nodeValue1 = { value: 1, key: 'key1' };
50+
const nodeValue2 = { value: 2, key: 'key2' };
51+
const nodeValue3 = { value: 3, key: 'key3' };
52+
53+
linkedList.append(nodeValue1).prepend(nodeValue3).insert(1, nodeValue2);
54+
55+
expect(linkedList.head.next.data).toEqual({ value: 2, key: 'key2' });
56+
});
57+
});

0 commit comments

Comments
 (0)