লিংকড লিস্ট হল একটি ডেটা স্ট্রাকচার যা ডেটা এলিমেন্টগুলো লিংকড ফর্মে সংরক্ষণ করে। লিংকড লিস্টের প্রতিটি নোডে একটি ডেটা এলিমেন্ট এবং একটি লিংক থাকে।
লিংকড লিস্ট রিভার্স প্রিন্ট করা একটি সাধারণ সমস্যা যা প্রোব্লেম সলভিং-এ সমাধান করতে হয়। এখানে আমরা C++-এ লিংকড লিস্ট রিভার্স প্রিন্ট করার একটি আকর্ষণীয় পদ্ধতি শিখব।
সাধারণত লিংকড লিস্ট রিভার্স প্রিন্ট করতে লিস্টে মডিফিকেশন আনার বা একাধিকবার ট্রাভার্স করার প্রয়োজন হয়। কিন্তু এই পদ্ধতিতে এমন কোনো জিনিসের প্রয়োজন নেই এবং লিংকড লিস্ট কেবল একবার ট্রাভার্স করে হয়ে যায়।
এই পদ্ধতির লজিক হল ক্যারেজ রিটার্ন (carriage return) ব্যবহার করে স্ট্রিং রিভার্সে প্রিন্ট করা। ক্যারেজ রিটার্ন হল প্রিন্টারকে (ডিসপ্লে ক্ষেত্রে কার্সর) একটি নির্দেশ যা লাইনে কিছু পজিশন ফাঁকা রেখে স্ক্রিনের একটি নির্দিষ্ট লোকেশনে যেতে বলে। এখন লজিক হল n (লিস্টের দৈর্ঘ্য) এডভান্স করা যাতে লিস্টের উপাদানগুলো প্রিন্ট করার জায়গা থাকে। প্রথম উপাদান প্রিন্ট করার আগে n-1 স্পেস ফাঁকা থাকবে, দ্বিতীয়ের জন্য n-2, এবং এভাবে কমতে থাকবে।
উদাহরণ কোড
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
using namespace std;
struct Node {
int data;
struct Node* next;
};
void printReverse(struct Node** head_ref, int n);
void push(struct Node** head_ref, int new_data);
int printList(struct Node* head);
int main() {
struct Node* head = NULL;
push(&head, 2);
push(&head, 7);
push(&head, 3);
push(&head, 5);
push(&head, 4);
push(&head, 6);
printf("Given linked list:\n");
int n = printList(head);
printf("\nReversed Linked list:\n");
printReverse(&head, n);
return 0;
}
void printReverse(struct Node** head_ref, int n) {
int j = 0;
struct Node* current = *head_ref;
while (current != NULL) {
for (int i = 0; i < 2 * (n - j); i++)
cout << " ";
cout << current->data << "\r";
current = current->next;
j++;
}
}
void push(struct Node** head_ref, int new_data) {
struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));
new_node->data = new_data;
new_node->next = (*head_ref);
(*head_ref) = new_node;
}
int printList(struct Node* head) {
int i = 0;
struct Node* temp = head;
while (temp != NULL) {
printf("%d ", temp->data);
temp = temp->next;
i++;
}
return i;
}
আউটপুট
Given linked list: 6 4 5 3 7 2 Reversed Linked list: 2 7 3 5 4 6