Fix the prepend method for the LinkedList (#47)

* Fix LinkedList

* Fix the prepend method for the LinkedList
This commit is contained in:
m-maksyutin 2018-06-04 05:21:42 +03:00 committed by Oleksii Trekhleb
parent 91d4714d19
commit beb8501aca
2 changed files with 13 additions and 3 deletions

View File

@ -21,7 +21,13 @@ export default class LinkedList {
*/ */
prepend(value) { prepend(value) {
// Make new node to be a head. // Make new node to be a head.
this.head = new LinkedListNode(value, this.head); const newNode = new LinkedListNode(value, this.head);
this.head = newNode;
// If there is no tail yet let's make new node a tail.
if (!this.tail) {
this.tail = newNode;
}
return this; return this;
} }

View File

@ -21,10 +21,14 @@ describe('LinkedList', () => {
it('should prepend node to linked list', () => { it('should prepend node to linked list', () => {
const linkedList = new LinkedList(); const linkedList = new LinkedList();
linkedList.append(1);
linkedList.prepend(2); linkedList.prepend(2);
expect(linkedList.head.toString()).toBe('2');
expect(linkedList.tail.toString()).toBe('2');
expect(linkedList.toString()).toBe('2,1'); linkedList.append(1);
linkedList.prepend(3);
expect(linkedList.toString()).toBe('3,2,1');
}); });
it('should delete node by value from linked list', () => { it('should delete node by value from linked list', () => {