Skip to content

Instantly share code, notes, and snippets.

@maciejmatu
Created June 21, 2017 08:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save maciejmatu/4be5552690272e99b51f0c1bf6606b93 to your computer and use it in GitHub Desktop.
Save maciejmatu/4be5552690272e99b51f0c1bf6606b93 to your computer and use it in GitHub Desktop.
// 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