Skip to content

Instantly share code, notes, and snippets.

@cauldyclark15
Created April 3, 2018 10:09
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 cauldyclark15/c0213aa5ebc522ec9230f4dbcbff37c7 to your computer and use it in GitHub Desktop.
Save cauldyclark15/c0213aa5ebc522ec9230f4dbcbff37c7 to your computer and use it in GitHub Desktop.
function LinkedList () {
let Node = function (element) {
this.element = element
this.next = null
}
let length = 0
let head = null
this.append = function (element) {
let node = new Node(element)
let current
if (head === null) {
head = node
} else {
current = head
while (current.next) {
current = current.next
}
current.next = node
}
length++
}
this.removeAt = function (position) {
if (position > -1 && position < length) {
let current = head
let previous
let index = 0
if (position === 0) {
head = current.next
} else {
while (index++ < position) {
previous = current
current = current.next
}
previous.next = current.next
}
length--
return current.element
}
}
this.insert = function (position, element) {
if (position >= 0 && position <= length) {
let node = new Node(element)
let current = head
let previous = null
let index = 0
if (position === 0) {
node.next = current
head = node
} else {
while (index++ < position) {
previous = current
current = current.next
}
node.next = current
previous.next = node
}
length++
return true
} else {
return false
}
}
this.toString = function () {
let current = head
let string = ''
while (current) {
string += `${current.element}${current.next ? ',' : ''}`
current = current.next
}
return string
}
}
// const myLinkedList = new LinkedList()
// myLinkedList.append('react')
// myLinkedList.append('node')
// myLinkedList.append('react native')
// console.log(myLinkedList.toString())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment