MyLinkedList

Run Settings
LanguageJavaScript
Language Version
Run Command
class MyLinkedList { constructor(value) { this.head = { value, next: null } this.tail = this.head; this.length = 1; } 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++; } 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++; } insertNode(value, index) { if(index >= this.length) { this.append(value); }else if(index <= 0) { 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++; } } 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; } } const firstLinkedList = new MyLinkedList(10); firstLinkedList.append(5); firstLinkedList.append(16); firstLinkedList.prepend(1); console.log(firstLinkedList.deleteNode(1)); firstLinkedList.insertNode(3, 1); console.log(firstLinkedList); console.log(firstLinkedList.reverse());
Editor Settings
Theme
Key bindings
Full width
Lines