Last active
March 13, 2019 01:05
-
-
Save dineshbalaji/92f69f00186e6e89f8d9b8e5f6a24da6 to your computer and use it in GitHub Desktop.
Doubly Linked List
This file contains 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 LinkedList { | |
constructor() { | |
this.head = null; | |
this.tail = null; | |
} | |
createElement(value, next, prev) { | |
return { value, next, prev } | |
} | |
addToHead(value) { | |
let node = this.createElement(value,null ,this.head) | |
this.head && (this.head.next = node); | |
!this.tail && (this.tail = node); | |
this.head = node; | |
return this; | |
} | |
addToTail(value) { | |
let node = this.createElement(value, this.tail, null); | |
(this.tail) && (this.tail.prev = node); | |
this.tail = node; | |
return this; | |
} | |
getMidItem() { | |
let p1,p2; | |
p1=p2=this.tail; | |
while(p2.next && p2.next.next) { | |
p1 = p1.next; | |
p2 = p2.next.next; | |
} | |
return p1; | |
} | |
*[Symbol.iterator](){ | |
let element = this.tail; | |
while(element) { | |
yield element.value; | |
element = element.next; | |
} | |
} | |
} | |
let list = new LinkedList(); | |
list.addToHead(2).addToHead(3).addToHead(4).addToHead(5).addToTail(1); | |
window.list = list; | |
console.log('head of List: ', list.head) | |
console.log('iterate List', [...list]) | |
console.log('getMidItem', list.getMidItem()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment