Created
June 21, 2017 08:53
-
-
Save maciejmatu/4be5552690272e99b51f0c1bf6606b93 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Singly Linked List data structure implementation | |
// in javascript. (not all methods) | |
class SinglyListNode { | |
constructor(data) { | |
this.data = data; | |
this.next = null; | |
} | |
} | |
class SinglyLinkedList { | |
constructor() { | |
this.head = null; | |
this.tail = null; | |
this.length = 0; | |
} | |
addLast(value) { | |
const node = new SinglyListNode(value); | |
if (this.length == 0) { | |
this.head = node; | |
} else { | |
this.tail.next = node; | |
} | |
this.tail = node; | |
this.length++; | |
return this; | |
} | |
addFirst(value) { | |
const node = new SinglyListNode(value); | |
const temp = this.head; | |
this.head = node; | |
this.head.next = temp; | |
if (this.length === 1) this.tail = temp; | |
this.length++; | |
return this; | |
} | |
removeFirst() { | |
if (this.length !== 0) { | |
if (this.length === 1) { | |
this.head = null; | |
this.tail = null; | |
} else { | |
this.head = this.head.next; | |
} | |
this.length--; | |
} | |
return this; | |
} | |
removeLast() { | |
if (this.length !== 0) { | |
if (this.length === 1) { | |
this.head = null; | |
this.tail = null; | |
} else { | |
let current = this.head; | |
while (current.next !== this.tail) { | |
current = current.next; | |
} | |
current.next = null; | |
this.tail = current; | |
} | |
this.length--; | |
} | |
return this; | |
} | |
clear() { | |
this.head = null; | |
this.tail = null; | |
this.length = 0; | |
return this; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment