Created
November 21, 2018 20:25
-
-
Save BideoWego/cf284542c0471edff65ad8836134346b to your computer and use it in GitHub Desktop.
Simple linked list implementation in javascript
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 Node { | |
constructor(value, next) { | |
this.value = value; | |
this.next = next; | |
} | |
} | |
class LinkedList { | |
constructor() { | |
this.head = null; | |
} | |
add(value) { | |
if (!this.head) { | |
return this.head = new Node(value); | |
} | |
var node = this.head; | |
while (node.next) { | |
node = node.next; | |
} | |
var n = node.next = new Node(value); | |
return n; | |
} | |
remove(node) { | |
if (node === this.head) { | |
return this.head = this.head.next; | |
} | |
var current = this.head; | |
var last = null; | |
while (current) { | |
if (node === current) { | |
last.next = current.next; | |
} | |
last = current; | |
current = current.next; | |
} | |
return node; | |
} | |
} | |
var ll = new LinkedList(); | |
ll.add(1); | |
console.log(ll); | |
// LinkedList { head: Node { value: 1, next: undefined } } | |
var node = ll.add(2); | |
console.log(ll); | |
// LinkedList { | |
// head: Node { value: 1, next: Node { value: 2, next: undefined } } } | |
ll.add(3); | |
console.log(ll); | |
// LinkedList { | |
// head: Node { value: 1, next: Node { value: 2, next: [Node] } } } | |
ll.remove(node); | |
console.log(ll); | |
// LinkedList { | |
// head: Node { value: 1, next: Node { value: 3, next: undefined } } } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment