Search This Blog

2023/05/06

Linked List in node.js

 class Node {

constructor(data) {
this.data = data
this.next = null
}
}

class LinkedList {
constructor(head = null) {
this.head = head
}

appendNode(newNode) {
var node = this.head;
if (node == null) {
this.head = newNode
} else {
while (node.next) {
node = node.next
}
node.next = newNode
}

}

insertAt(index, newNode) {
if (index == 0) {
var tempVal = this.head
newNode.next = tempVal
this.head = newNode
} else {
var i = 1
var firstNode = this.head
while (i < index - 1) {
firstNode = firstNode.next
if (firstNode == null) {
console.log("Index out of bound")
return
}
i++
}
var tempVal = firstNode.next
newNode.next = tempVal
firstNode.next = newNode
}
}

listSize() {
var firstNode = this.head;
var i = 0;
while (firstNode) {
firstNode = firstNode.next
i++
}
return i;
}

isEmpty() {
return (this.head == null)
}

getFirst() {
return this.head;
}


getLast() {
var firstNode = this.head
while (firstNode.next) {
firstNode = firstNode.next
}
return firstNode
}


removeFrom(index) {
if (index == 0) {
var tempVal = this.head
this.head = tempVal.next
} else {
var i = 0;
var firstNode = this.head;
var previousNode = null;
while (i < index - 1) {
previousNode = firstNode
firstNode = firstNode.next
i++
if (firstNode == null) {
console.log("Index Out of bound")
return;
}
}
if (previousNode == null) {
this.head = firstNode.next
} else {
previousNode.next = firstNode.next
}
}
}

getNode(index) {
if (index == 0) {
return this.head
} else {
var firstNode = this.head
var i = 0;
while (i < index - 1) {
firstNode = firstNode.next
i++
}
return firstNode
}
}

clear() {
this.head = null;
}

reverse() {
let previousNode = null
let currentNode = this.head;
if (currentNode == null) return;

let nextNode = null
while (currentNode) {
nextNode = currentNode.next;
currentNode.next = previousNode
previousNode = currentNode
currentNode = nextNode
}
this.head = previousNode

}

indexOf(data) {
var firstNode = this.head
var j = 0
while (firstNode) {
if (firstNode.data == data) {
return j
}
firstNode = firstNode.next
j++
}
}


printList() {
let node = this.head;
process.stdout.write("HEAD->")
while (node) {
process.stdout.write(node.data + "->");
node = node.next;
}
console.log("NULL");
}
}

let myList = new LinkedList();
let node = new Node(5);

myList.appendNode(node);
myList.appendNode(new Node(11));
myList.appendNode(new Node(7));
myList.appendNode(new Node(17));
myList.appendNode(new Node(87));
myList.printList();

myList.insertAt(6, new Node(21));
myList.printList();

myList.removeFrom(6)
myList.printList();

var size = myList.listSize()
console.log("size", size)

var n = myList.getNode(2)
console.log("item at index 2", n)

// myList.clear()
// var size1 = myList.listSize()
// console.log("size", size1)

myList.reverse()
myList.printList();

var y = myList.indexOf(7)
console.log("indexof 7", y)

var lastNode = myList.getLast()
console.log("lastNode",lastNode)

No comments:

Post a Comment