Last active
February 27, 2019 03:25
-
-
Save anuraagdjain/c8877e68e2a6df19f1a129c9e805fcfe to your computer and use it in GitHub Desktop.
LinkedList
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
| 'use strict'; | |
| class LinkList { | |
| constructor() { | |
| this.head = null; | |
| } | |
| addNode(value) { | |
| const node = new Node(value); | |
| if (this.head) { | |
| node.next = this.head; | |
| } | |
| this.head = node; | |
| } | |
| delete(value = null) { | |
| /** | |
| * if `value` given delete that, else delete the first node. | |
| */ | |
| if (value) { | |
| let curr = this.head, | |
| prev = null; | |
| while (curr != null) { | |
| if (curr.data === value) { | |
| prev.next = curr.next; | |
| curr = null; | |
| break; | |
| } | |
| prev = curr; | |
| curr = curr.next; | |
| } | |
| } else { | |
| this.head = this.head.next; | |
| } | |
| } | |
| listNodes() { | |
| let node = this.head; | |
| while (node != null) { | |
| console.log(node.data); | |
| node = node.next; | |
| } | |
| } | |
| } | |
| class Node { | |
| constructor(data) { | |
| this.data = data; | |
| this.next = null; | |
| } | |
| } | |
| let list = new LinkList(); | |
| list.addNode(100); | |
| list.addNode(200); | |
| list.addNode(300); | |
| list.addNode(400); | |
| list.delete(200); | |
| console.log('After deleting 200'); | |
| list.listNodes(); | |
| console.log('\nAfter deleting first node'); | |
| list.delete(); | |
| list.listNodes(); | |
| /* | |
| Output: | |
| =============== | |
| After deleting 200 | |
| 400 | |
| 300 | |
| 100 | |
| After deleting first node | |
| 300 | |
| 100 | |
| */ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment