Singly Linked List: Insert Operation (এলিমেন্ট যোগ করা)
সিংলি লিংকড লিস্টে নতুন নোড ইনসার্ট করার জন্য next পয়েন্টারগুলো সঠিকভাবে রি-লিংক করতে হয়।
Insert Algorithm Steps
- নতুন
Nodeতৈরি করুন। - লিস্ট খালি কিনা চেক — হলে হেডে সেট করুন।
- টার্গেট পজিশন পর্যন্ত ট্রাভার্স (
currNode = currNode.next)। - লিংক আপডেট:
- নতুন নোডের
next=currNode.next(বাকি লিস্ট সংরক্ষণ)۔ currNode.next= নতুন নোড (নতুন নোড লিস্টে যুক্ত)۔
- নতুন নোডের
- Length ইনক্রিমেন্ট।
Insert মেথড ইমপ্লিমেন্টেশন
class LinkedList {
constructor() {
this.head = null;
this.length = 0;
}
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; // 1. New node points to rest of list
currNode.next = node; // 2. Current node points to new node
this.length++;
return node;
}
display() {
let currNode = this.head;
let output = "";
while (currNode !== null) {
output += currNode.data + " -> ";
currNode = currNode.next;
}
console.log(output + "null");
}
}
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 (0-indexed: after 1st node)
list.display();
// Output: 10 -> 30 -> 15 -> 20 -> null
আউটপুট ব্যাখ্যা
Insert Sequence:
1. insert(10) -> [10]
2. insert(20) -> [10, 20] (pos=1, end)
3. insert(30) -> [10, 20, 30] (pos=2, end)
4. insert(15, 2) -> Position 2: after 1st node (10)
Traverse: currNode = 10 (iter=1 < 2)
Insert after 10: 10 -> 15 -> 20 -> 30
Final: 10 -> 15 -> 20 -> 30 -> null
করেকশন: আউটপুটে 10 -> 30 -> 15 -> 20 দেখানো হয়েছে কিন্তু সঠিক আউটপুট 10 -> 15 -> 20 -> 30 হওয়া উচিত (পজিশন ২ মানে ১০ এর পরে)۔
Default Position: this.length
পজিশন না দিলে ডিফল্টভাবে শেষে (append) ইনসার্ট হয়। এটি কনভেনিয়েন্স মেথড হিসেবে কাজ করে।
ভিজ্যুয়াল: Insert at Middle
BEFORE: HEAD → [10] → [20] → [30] → null
↑
Insert Position 2 (after 10)
STEP 1: Create Node(15)
STEP 2: Traverse to Node(10)
STEP 3: Link Updates:
Node(15).next = Node(20) // Save rest of list
Node(10).next = Node(15) // Link new node
AFTER: HEAD → [10] → [15] → [20] → [30] → null