Skip to content

Instantly share code, notes, and snippets.

@gbuszmicz
Last active December 22, 2016 14:36
Show Gist options
  • Save gbuszmicz/34c1d936a1b80183a4fc07dc81117c26 to your computer and use it in GitHub Desktop.
Save gbuszmicz/34c1d936a1b80183a4fc07dc81117c26 to your computer and use it in GitHub Desktop.
Singly linked list in JS
const LinkedList = () => {
let _list = {
head: null,
tail: null,
length: 0
}
// Node creator
let Node = (data) => {
let node = {
data: data,
next: null
};
return node
}
return { // Public methods
// Add node to tail (last element)
push (data) {
let node = Node(data)
if (!_list.head) {
_list.head = node
_list.tail = node
} else {
_list.tail.next = node
_list.tail = node
}
_list.length++
},
// Remove last node (tail)
pop () {
if (_list.length == 0) {
throw new Error('List has no elements')
} else {
let tempNode = _list.head
while(tempNode.next.next) { // Last node (tail) has next = null;
tempNode = tempNode.next
}
tempNode.next = null;
_list.length--
}
},
// Add node to head (first element)
unshift (data) {
let node = Node(data)
if (!_list.head) {
_list.head = node
_list.tail = node
} else {
let currentHead = _list.head
_list.head = node
_list.head.next = currentHead
}
_list.length++
},
// Remove first node (head)
shift () {
if (_list.length == 0) {
throw new Error('List has no elements')
} else {
let currentHead = _list.head
_list.head = currentHead.next
_list.length--
}
},
size () {
return _list.length
},
elements () {
return _list.head
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment