LinkedList
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148
class Node {
constructor(value){
this.value = value;
this.next = null;
}
}
class LinkedList {
constructor(value){
this.head = new Node(value);
this.tail = this.head;
this.length = 1;
}
printList(){
let outputArr = [];
let currPointer = this.head;
while(currPointer.next != null){
outputArr.push(currPointer.value);
currPointer = currPointer.next;
}
outputArr.push(currPointer.value);
console.log(outputArr.join('-->'));
}
append(value){
let newNode = new Node(value);
this.tail.next = newNode;
this.tail = newNode;
this.length++;
return this;
}
prepend(value){
let newNode = new Node(value);
newNode.next = this.head;
this.head = newNode;
this.length++;
return this;
}
insert(index, value){
if(index == 0){
this.prepend(value);
return this;
}
if(index >= this.length){
this.append(value);
return this;
}
let newNode = new Node(value);
let currPointer = this.head;
let idx = 0;
while(currPointer.next != null){
if(idx+1 == index){
newNode.next = currPointer.next;
currPointer.next = newNode;
return this;
}
currPointer = currPointer.next;
idx++;
}
this.length++;
return this;
}
remove(index){
if(index >= this.length){
return "Cannot remove"
}
if(index == 0){
let tempHead = this.head.next;
this.head = tempHead;
this.length--;
return this;
}
let currPointer = this.head;
let idx = 0;
while(currPointer != null && idx != index-1){
currPointer = currPointer.next;
idx++;
}
if(currPointer.next != null){
let tempHead = currPointer.next.next;
currPointer.next = tempHead;
}
this.length--;
return this;
}
reverse(){
if(!this.head.next){
return this;
}
let first = this.head;
this.tail = first;
let second = this.head.next;
while(second){
let temp = second.next;
second.next = first;
first = second;
second = temp;
}
this.head.next = null;
this.head = first;
return this;
}
}
const myLinkedList = new LinkedList(10);
myLinkedList.append(5);
myLinkedList.append(3);
myLinkedList.append(16);
myLinkedList.prepend(1);
myLinkedList.printList();
myLinkedList.insert(5, 11);
myLinkedList.printList();
console.log("****************************")
myLinkedList.remove(5);
myLinkedList.printList();
let tempLinkedList = myLinkedList.reverse();
tempLinkedList.printList();
JavaScript
INFO