Skip to content

Instantly share code, notes, and snippets.

@joelbarbosa
Last active December 4, 2018 21:59
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 joelbarbosa/d0348abb06dcf64e7842f0d5cf40b8ed to your computer and use it in GitHub Desktop.
Save joelbarbosa/d0348abb06dcf64e7842f0d5cf40b8ed to your computer and use it in GitHub Desktop.
function createNode(value) {
return {
value: value,
next: null
}
};
function createLinkedList() {
return {
head: null,
tail: null,
length: 0,
push(value) {
const node = createNode(value);
if (this.head === null) {
this.head = node;
this.tail = node;
this.length++;
return node;
}
this.tail.next = node;
this.tail = node;
this.length++;
return node;
},
pop() {
if (this.isEmpty()) {
return null;
}
const node = this.tail;
if (this.head === this.tail) {
this.head = null;
this.tail = null;
this.length--;
return node;
}
let current = this.head;
let penultimate;
while (current){
if (current.next === this.tail) {
penultimate = current;
break;
}
current = current.next;
}
penultimate.next = null;
this.tail = penultimate;
this.length--;
return node;
},
get(index) {
if (index < 0 || index > this.length) {
return null;
}
if (index === 0) {
return this.head;
}
let current = this.head;
let i = 0;
while (i < index) {
i++;
current = current.next;
}
return current;
},
delete(index) {
if (index < 0 || index > this.length) {
return null;
}
if (index === 0) {
const deleted = this.head;
this.head = this.head.next;
this.length--;
return deleted;
}
let current = this.head;
let previous
let i = 0;
while (i < index) {
i++;
previous = current;
current = current.next;
}
const deleted = current;
previous.next = current.next;
this.length--;
return deleted;
},
isEmpty() {
return this.length === 0;
},
print() {
const values = [];
let current = this.head;
while (current) {
values.push(current.value);
current = current.next;
}
return values.join(' => ');
}
}
}
const list = createLinkedList();
const values = ['a', 'b', 'c', 'd', 'e'];
const nodes = values.map(v => list.push(v));
console.log(list.isEmpty());
console.log(list.print())
//"a => b => c => d => e"
list.pop();
console.log(list.print())
console.log(list.head)
console.log(list.tail)
console.log(list.get(2))
list.delete(2)
console.log(list.print())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment