Add LinkedList.

This commit is contained in:
Oleksii Trekhleb 2018-03-27 15:12:44 +03:00
parent 335e751f32
commit 60e141f18f
2 changed files with 63 additions and 5 deletions

View File

@ -28,7 +28,35 @@ export default class LinkedList {
}
prepend(value) {
const newNode = new Node(value);
this.head = new Node(value, this.head);
return newNode;
}
delete(value) {
if (!this.head) {
return null;
}
let deletedNode = null;
if (this.head.value === value) {
deletedNode = this.head;
this.head = this.head.next;
}
let currentNode = this.head;
while (currentNode.next) {
if (currentNode.next.value === value) {
deletedNode = currentNode.next;
currentNode.next = currentNode.next.next;
}
currentNode = currentNode.next;
}
return deletedNode;
}
toArray() {

View File

@ -3,21 +3,51 @@ import LinkedList from '../LinkedList';
describe('LinkedList', () => {
it('should create empty linked list', () => {
const linkedList = new LinkedList();
expect(linkedList).toBeDefined();
expect(linkedList.toString()).toBe('');
});
it('should append node to linked list', () => {
const linkedList = new LinkedList();
linkedList.append(1);
linkedList.append(2);
const node1 = linkedList.append(1);
const node2 = linkedList.append(2);
expect(node1.value).toBe(1);
expect(node2.value).toBe(2);
expect(linkedList.toString()).toBe('1,2');
});
it('should prepend node to linked list', () => {
const linkedList = new LinkedList();
const node1 = linkedList.append(1);
const node2 = linkedList.prepend(2);
expect(node1.value).toBe(1);
expect(node2.value).toBe(2);
expect(linkedList.toString()).toBe('2,1');
});
it('should delete node by value from linked list', () => {
const linkedList = new LinkedList();
linkedList.append(1);
linkedList.append(2);
linkedList.prepend(3);
expect(linkedList.toString()).toBe('3,1,2');
linkedList.append(3);
linkedList.append(3);
linkedList.append(4);
linkedList.append(5);
const deletedNode = linkedList.delete(3);
expect(deletedNode.value).toBe(3);
expect(linkedList.toString()).toBe('1,2,3,4,5');
linkedList.delete(3);
expect(linkedList.toString()).toBe('1,2,4,5');
linkedList.delete(1);
expect(linkedList.toString()).toBe('2,4,5');
});
});