Created
August 6, 2020 14:15
-
-
Save Youngestdev/28feb5fe1a02bf231fb4dd16f99ff191 to your computer and use it in GitHub Desktop.
Revitalizing my dead JavaScript by building data structures. Here's an incomplete LinkedList that'll be updated over time.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Node { | |
constructor(data = 0, next=null) { | |
this.data = data; | |
this.next = next | |
} | |
} | |
class LinkedList { | |
constructor(value = 0){ | |
this.head = new Node(value) | |
} | |
prepend(value) { | |
let current = this.head | |
let new_node = new Node(value) | |
new_node.next = current | |
this.head = new_node | |
return current | |
} | |
getValues() { | |
let current = this.head | |
let result = [] | |
while (current != null) { | |
result.push(current.data) | |
current = current.next | |
} | |
return result | |
} | |
append(value) { | |
let head = this.head | |
let new_node = new Node(value) | |
if (head == null) { | |
head = new_node | |
return head | |
} | |
while(head && head.next != null) { | |
head = head.next | |
} | |
head.next = new_node | |
return head | |
} | |
length() { | |
let count = 0 | |
let head = this.head | |
while (head != null) { | |
count += 1 | |
head = head.next | |
} | |
return count | |
} | |
reverse() { | |
let current = this.head | |
// 1 - 2 - 3 - 4 | |
let prev = null | |
let next = null | |
while (current != null) { | |
next = current.next // 2 | |
current.next = prev // 1 -> null | |
prev = current | |
current = next | |
} | |
// return prev | |
this.head = prev | |
return this.head | |
} | |
} | |
const example = new LinkedList(10) | |
example.prepend(14) | |
example.append(19) | |
example.append(15) | |
example.reverse() | |
console.log(example.getValues()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I think the Add* methods are incorrect. I'll reimplement them but lmao, JavaScript isn't sweet with DS abeg.
Binary tree (Incomplete):