Skip to content

Instantly share code, notes, and snippets.

@AndrewThian
Created February 9, 2019 05:27
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 AndrewThian/c9d43e59d3fd41f2960a8a8f18314e88 to your computer and use it in GitHub Desktop.
Save AndrewThian/c9d43e59d3fd41f2960a8a8f18314e88 to your computer and use it in GitHub Desktop.
Implementing datastructures: singly linked list
class LinkedList {
constructor(head=null) {
this.head = head;
this.count = 0;
}
add (newData) {
// create node
// reference previous node to new node
let temp = new Node(null, newData);
let current = this.head;
if (current === null) {
this.head = temp
this.count += 1
}
while(current.getNext() !== null) {
current = current.getNext();
}
current.setNext(temp)
this.count += 1
}
get (index) {
if (index <= 0) {
return -1
}
let current = this.head;
for (let i = 1; i < index; i++) {
current = current.getNext();
}
return current.getData();
}
size () {
return this.count
}
isEmpty () {
return this.head === null;
}
remove () {
let current = this.head;
if (current === null) {
return -1
}
if (this.count === 1) {
current = current.getNext()
current.setNext(null)
return
}
while(current.getNext().getNext() !== null) {
current = current.getNext();
}
current.setNext(null)
this.count -= 1
}
}
class Node {
constructor(next=null, data) {
this.next = next
this.data = data;
}
getData () {
return this.data
}
getNext () {
return this.next
}
setData (newData) {
this.data = newData;
}
setNext (newNode) {
this.next = newNode;
}
}
const node = new Node(null, "node 1 data")
const linkedlist = new LinkedList(node)
linkedlist.add("node 2 data")
linkedlist.add("node 3 data")
linkedlist.remove();
console.log(linkedlist.size())
console.log(linkedlist)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment