Singly Linked List: সম্পূর্ণ ক্লাস ইমপ্লিমেন্টেশন
সিংলি লিংকড লিস্টে প্রতিটি নোডের শুধু next পয়েন্টার থাকে। নিচে সম্পূর্ণ ফিচারসহ ক্লাস দেওয়া হলো।
সম্পূর্ণ LinkedList Class
class LinkedList {
constructor() {
this.head = null;
this.length = 0;
}
// Insert at Position (Default: End)
insert(data, position = this.length) {
const node = new LinkedList.Node(data);
// Empty List
if (this.head === null) {
this.head = node;
this.length++;
return this.head;
}
// Traverse to Position
let iter = 1;
let currNode = this.head;
while (currNode.next !== null && iter < position) {
currNode = currNode.next;
iter++;
}
// Link Updates
node.next = currNode.next;
currNode.next = node;
this.length++;
return node;
}
// Remove at Position (Default: Head)
remove(data, position = 0) {
if (this.length === 0) {
console.log("List is already empty");
return;
}
this.length--;
let currNode = this.head;
// Case 1: Remove Head (Position <= 0)
if (position <= 0) {
this.head = this.head.next;
}
// Case 2: Remove Tail (Position >= Length)
else if (position >= this.length) {
while (currNode.next.next !== null) {
currNode = currNode.next;
}
currNode.next = null;
}
// Case 3: Remove Middle
else {
let iter = 0;
while (iter < position) {
currNode = currNode.next;
iter++;
}
currNode.next = currNode.next.next;
}
return currNode;
}
// Display List
display() {
let currNode = this.head;
let output = "";
while (currNode !== null) {
output += currNode.data + " -> ";
currNode = currNode.next;
}
console.log(output + "null");
}
}
// Node Class
LinkedList.prototype.Node = class {
constructor(data) {
this.data = data;
this.next = null;
}
};
ব্যবহারের উদাহরণ
const list = new LinkedList();
list.insert(10); // 10
list.insert(20); // 10 -> 20
list.insert(30); // 10 -> 20 -> 30
list.insert(15, 2); // Position 2: 10 -> 15 -> 20 -> 30
list.display();
// Output: 10 -> 15 -> 20 -> 30 -> null
list.remove(1); // Remove at position 1 (15)
list.display();
// Output: 10 -> 20 -> 30 -> null
list.remove(); // Remove Head (Default position 0)
list.display();
// Output: 20 -> 30 -> null
Time Complexity
| Operation | Complexity | Note |
|---|---|---|
| Insert at Head | O(1) | Direct head update |
| Insert at Tail | O(n) | Traversal needed (no tail pointer) |
| Insert at Middle | O(n) | Traversal to position |
| Remove Head | O(1) | Direct head update |
| Remove Tail | O(n) | Traversal to 2nd last |
| Search/Access by Index | O(n) | Sequential access only |
| Display | O(n) | Full traversal |
Improvement Ideas
- Add
tailpointer for O(1) tail insertion. - Add
get(index),indexOf(value)মেথড। - Implement
reverse()(Iterative/Recursive)。—— - ES6 Iterator Protocol (
Symbol.iterator) অ্যাড করুনfor...ofলুপের জন্য।