Created
January 8, 2022 22:23
-
-
Save lloydbanks/276b1e5dba1295f102e0a14b5a7040d0 to your computer and use it in GitHub Desktop.
[Data Structures] Linked List
This file contains hidden or 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 LinkedNode { | |
constructor(data, next = null) { | |
this.data = data | |
this.next = next | |
} | |
} | |
class LinkedList { | |
constructor() { | |
this.head = null | |
this.tail = null | |
} | |
append(data) { | |
const node = new LinkedNode(data) | |
if (!this.head) { | |
this.head = node | |
} | |
if (this.tail) { | |
this.tail.next = node | |
} | |
this.tail = node | |
} | |
prepend(data) { | |
const node = new LinkedNode(data, this.head) | |
if (!this.tail) { | |
this.tail = node | |
} | |
this.head = node | |
} | |
toArray() { | |
const output = [] | |
let current = this.head | |
while (current) { | |
output.push(current.data) | |
current = current.next | |
} | |
return output | |
} | |
find(data) { | |
let current = this.head | |
while (current) { | |
if (current.data === data) { | |
return current | |
} | |
current = current.next | |
} | |
} | |
insertAfter(after, data) { | |
const found = this.find(after) | |
found.next = new LinkedNode(data, found.next) | |
} | |
remove(data) { | |
let current = this.head | |
while (this.head && this.head.data === data) { | |
this.head = this.head.next | |
} | |
while (current.next) { | |
if (current.next.data === data) { | |
current.next = current.next.next | |
} else { | |
current = current.next | |
} | |
} | |
if (this.tail.data === data) { | |
this.tail = current | |
} | |
} | |
} | |
const list = new LinkedList() | |
list.append('test1') | |
list.append('test2') | |
list.append('test3') | |
list.prepend('test0') | |
list.insertAfter('test2', 'test2copy') | |
list.remove('test2copy') | |
// list.find('test1') | |
// list.toArray() | |
list |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment