Queues

Run Settings
LanguageJavaScript
Language Version
Run Command
class MyLinkedList { constructor(value) { if(value === undefined) { this.head = null; this.length = 0; }else { this.head = { value, next: null } this.length = 1; } this.tail = this.head; } newNode(value) { return { value, next: null }; } append(value) { const node = this.newNode(value); if(this.tail === null) { this.tail = node; this.head = this.tail; }else { this.tail.next = node; this.tail = this.tail.next; } this.length++; return this; } prepend(value) { const node = this.newNode(value); if(this.head === null) { this.head = node; this.tail = this.head; }else { node.next = this.head; this.head = node; } this.length++; return this; } insertNode(value, index) { if(index >= this.length) { return this.append(value); }else if(index <= 0) { return this.prepend(value); }else { const node = this.newNode(value); const prevNode = this.traversal(index-1); const nextNode = prevNode.next; prevNode.next = node; node.next = nextNode; this.length++; return this; } } deleteNode(index) { if(this.length === 0 || index < 0 || index >= this.length) { return false; }else { if(index === 0) { if(this.length === 1) { this.head = null; this.tail = null; this.length = 0; }else { this.head = this.head.next; this.length--; } }else { const prevNode = this.traversal(index-1); const nextNode = prevNode.next; prevNode.next = nextNode.next; nextNode.next = null; this.length--; if(nextNode === this.tail) { this.tail = prevNode; } } return true; } } reverse() { if(this.length <= 1) { return this; } let prevNode = null, curNode = this.head; while(curNode !== null) { const temp = curNode.next; curNode.next = prevNode; prevNode = curNode; curNode = temp; } this.tail = this.head; this.head = prevNode; return this; } traversal(index) { let current = this.head; for(let i=0;i < index && current !== null;i++) { current = current.next; } return current; } } class Queues { constructor() { this.data = new MyLinkedList(); } enque(value) { return this.data.append(value); } dequeue() { const val = this.data.head ? this.data.head.value : null; if(typeof val !== "undefined") { this.data.deleteNode(0); } return val; } peak() { return this.data.head ? this.data.head.value : null; } }
Editor Settings
Theme
Key bindings
Full width
Lines