UNPKG

linked-list-group-reversal-502

Version:

linked list with group reversal

119 lines (96 loc) 2.59 kB
const readline = require("readline"); // Node class for representing individual nodes in the linked list class Node { constructor(data) { this.data = data; this.next = null; } } // LinkedList class that manages the linked list operations class LinkedList { constructor() { this.head = null; } // Method to append a new node at the end of the list append(data) { const newNode = new Node(data); if (!this.head) { this.head = newNode; return; } let current = this.head; while (current.next) { current = current.next; } current.next = newNode; } // Method to reverse the linked list in groups of k reverseInGroups(k) { if (this.head === null || k <= 1) return; let current = this.head; let prevTail = null; while (current) { let count = 0; let groupHead = current; let prev = null; let next = null; // Reverse the group of 'k' nodes while (current && count < k) { next = current.next; current.next = prev; prev = current; current = next; count++; } if (!prevTail) { this.head = prev; } else { prevTail.next = prev; } groupHead.next = current; prevTail = groupHead; } } // Method to print the linked list print() { let current = this.head; let result = ""; while (current) { result += current.data + " -> "; current = current.next; } result += "null"; console.log(result); } } // Setup readline interface for user input const rl = readline.createInterface({ input: process.stdin, output: process.stdout, }); // Function to ask user for input function askQuestion(query) { return new Promise((resolve) => rl.question(query, resolve)); } // Main function to execute the program async function main() { const list = new LinkedList(); const values = await askQuestion( "Enter the values for the linked list (comma separated): " ); const valueArray = values.split(",").map((value) => value.trim()); for (const value of valueArray) { list.append(parseInt(value)); } const k = await askQuestion( "Enter the value of k (group size for reversal): " ); console.log("Original List:"); list.print(); list.reverseInGroups(parseInt(k)); console.log(`List After Reversing in Groups of ${k}:`); list.print(); rl.close(); } // Run the main function main();