class Node {
constructor(val) {
this.val = val;
this.next = null;
}
}
class LinkedList {
constructor() {
this.length = 0;
this.head = null;
}
/**
* get value of node by index
* @param {index} number
* @return {number}
*/
get(index) {
if (this.length === 0 || index >= this.length) {
return -1;
}
let node = this.head;
for (let i = 0; i < index; i++) {
node = node.next;
}
return node.val;
}
/**
* add node at head
* @param {val} number
* @return {void}
*/
addHead(val) {
let newNode = new Node(val);
if (this.head === null) {
this.head = newNode;
} else {
newNode.next = this.head;
this.head = newNode;
}
this.length++;
}
/**
* add node at tail
* @param {val} number
* @return {void}
*/
addTail(val) {
let newNode = new Node(val);
if (this.length === 0) {
this.head = newNode;
this.length++;
return;
}
let node = this.head;
for (let i = 0; i < this.length - 1; i++) {
node = node.next;
}
node.next = newNode;
this.length++;
}
/**
* add node by index
* @param {number} index
* @param {number} val
* @return {void}
*/
addByIndex(index, val) {
if (index > this.length) {
return;
}
let newNode = new Node(val);
if (index === 0) {
newNode.next = this.head;
this.head = newNode;
this.length++;
return;
}
let node = this.head;
for (let i = 0; i < index - 1; i++) {
node = node.next;
}
let prevNode = node;
let curNode = prevNode.next;
prevNode.next = newNode;
newNode.next = curNode;
this.length++;
}
/**
* delete node by index
* @param {number} index
* @return {void}
*/
deleteByIndex(index) {
if (index > this.length - 1) {
return;
}
if (index === 0) {
this.head = this.head.next;
this.length--;
return;
}
let node = this.head;
let prevNode = node;
for (let i = 0; i < index; i++) {
prevNode = node;
node = node.next;
}
prevNode.next = node.next;
this.length--;
}
}
//create linked list
myList = new LinkedList;
//populate linked list
myList.addByIndex(0, 2);
myList.addTail(3);
myList.addHead(1);
myList.addTail(4);
myList.deleteByIndex(3);