@dibzthedibz/linked-list-library
Version:
Methods to act upon linked lists
113 lines (109 loc) • 3.4 kB
JavaScript
class LinkedList {
constructor() {
this.head = null
this.tail = null
this.size = 0
}
//Inserts a new node at the head of the list.
insertAtHead(data) {
const newNode = new LinkedListNode(data, this.head)
this.head = newNode
if (this.tail === null) {
this.tail = newNode
}
this.size++
}
//Inserts a new node at the tail of the list.
insertAtTail(data) {
const newNode = new LinkedListNode(data, null)
if (this.tail !== null) {
this.tail.next = newNode;
}
this.tail = newNode;
if (this.head === null) {
this.head = newNode
}
this.size++
}
//Inserts a new node at the specified position.
insertInMiddle(data, position) {
if (position <= 0) {
this.insertAtHead(data);
return
}
else if (position >= this.size) {
this.insertAtTail(data)
return
}
const prev = this.findNodeAt(position - 1);
console.log(`Previous node at position ${position - 1}: ${JSON.stringify(prev)}`);
const newNode = new LinkedListNode(data, prev.next);
prev.next = newNode;
this.size++;
console.log(`Node ${data} inserted at position ${position}`);
}
//Finds and returns the node at the specified position.
findNodeAt(position) {
let current = this.head
let index = 0
while (current !== null && index < position) {
current = current.next
index++
}
if (current === null) {
console.log(`Node not found at position ${position}`);
} else {
console.log(`Found node at position ${position}: ${JSON.stringify(current)}`);
}
return current;
}
//Converts an array to a linked list.
arrayToList(arr) {
for (let i = arr.length - 1; i >= 0; i--) {
this.insertAtHead(arr[i]);
}
return this;
}
//Converts the linked list to an array.
listToArray() {
let result = [];
let curr = this.head;
while (curr !== null) {
result.push(curr.value);
curr = curr.next;
}
return result;
}
//Makes the list circular by pointing the tail to the node at the specified position.
makeCircular(position) {
const targetNode = this.findNodeAt(position);
if (this.tail !== null && targetNode !== null) {
this.tail.next = targetNode;
} else {
console.log(`unable to create circular reference at position ${position}`);
}
}
//Checks if the list is circular and returns true or false.
isCircular() {
if (this.head === null) {
return false;
}
let slow = this.head;
let fast = this.head;
while (fast !== null && fast.next !== null) {
slow = slow.next;
fast = fast.next.next;
if (slow === fast) {
return true;
}
}
return false;
}
}
class LinkedListNode {
constructor(value, next) {
this.value = value
this.next = next
}
}
module.exports = LinkedList