Created
June 19, 2017 21:16
-
-
Save ali-k-h/f2195200fc467257a274e3360f76869a to your computer and use it in GitHub Desktop.
Doubly Linked List basic implementation ES6 ECMAPScript 6
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 DoublyLinkedList{ | |
| constructor(){ | |
| this.head = null | |
| this.tail = null | |
| this.count = 0 | |
| } | |
| size(){ | |
| return this.count | |
| } | |
| add(key, value){ | |
| if(!key || !value) throw new Error('NO INPUT') | |
| const node = { | |
| key:key, | |
| value:value, | |
| next:null, | |
| prev:null | |
| } | |
| if(this.count === 0){ | |
| this.head = node | |
| this.tail = node | |
| } | |
| else{ | |
| let temp = this.tail | |
| this.tail = node | |
| temp.next = this.tail | |
| this.tail.prev = temp | |
| } | |
| this.count++ | |
| } | |
| find(key){ | |
| if(!key) throw new Error('NO INPUT') | |
| let node = this.head | |
| while(node){ | |
| if(node.key === key){ | |
| return node | |
| } | |
| else{ | |
| node = node.next | |
| } | |
| } | |
| return null | |
| } | |
| remove(key){ | |
| if(!key) throw new Error('NO INPUT') | |
| let node = this.find(key) | |
| if (!node) return false | |
| let prev = node.prev | |
| let next = node.next | |
| prev.next = next | |
| next.prev = prev | |
| this.count-- | |
| return true | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment