Skip to content

Instantly share code, notes, and snippets.

@Youngestdev
Created August 6, 2020 14:15
Show Gist options
  • Save Youngestdev/28feb5fe1a02bf231fb4dd16f99ff191 to your computer and use it in GitHub Desktop.
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.
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())
@Youngestdev
Copy link
Author

Youngestdev commented Aug 6, 2020

I think the Add* methods are incorrect. I'll reimplement them but lmao, JavaScript isn't sweet with DS abeg.
Binary tree (Incomplete):

class BinaryTreeNode {
    constructor(data, left = null, right = null) {
        this.data = data
        this.left = left
        this.right = right
    }
}

class BinaryTree {
    constructor(value){
        this.root = new BinaryTreeNode(value)
    }    

    AddLeftLeaf(leaf, value) {
        leaf.root.left = new BinaryTreeNode(value)
    }

    AddRightLeaf(leaf, value) {
        leaf.root.right = new BinaryTreeNode(value)
    }
}

let example = new BinaryTree(0)
example.AddLeftLeaf(example, 1)
example.AddRightLeaf(example, 2)
example.AddLeftLeaf(example, 3)
example.AddRightLeaf(example, 4)
console.log(example, '\n')

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment