লিঙ্কযুক্ত তালিকা গতিশীলভাবে মেমরি বরাদ্দ করে, একটি স্ট্যাক বাস্তবায়ন করতে ব্যবহৃত হয়। এই প্রোগ্রামটি c++ প্রোগ্রামিং-এ লিংক লিস্টের বিপরীত চিত্র প্রদর্শন করে। এখানে, প্রার্থী প্রত্যাশিত ফলাফল পেতে নিম্নলিখিত পদ্ধতি অবলম্বন করতে পারেন। অ্যালগরিদম নিম্নরূপ;
অ্যালগরিদম
START Step 1: create an empty stack of type node pointer Step 2: Traverse the list and push all of its nodes onto a stack Step 4: Traverse the list from the head node again Step 5: pop a value from the stack top step 6: connect them in reverse order Step 7: PRINT STOP
উপরের অ্যালগরিদমের উপর ভিত্তি করে, নিম্নলিখিত c++ কোডটি খসড়া করা হয়েছে যেখানে stdlib লাইব্রেরি ফাইল প্রবন্ধ একটি মূল ভূমিকা স্ট্যাক সম্পর্কিত কী পদ্ধতিগুলি নিম্নলিখিত হিসাবে ব্যবহার করে;
উদাহরণ
#include <iostream>
#include <stdlib.h>
using namespace std;
struct linked_list {
int data;
struct linked_list *next;
};
int stack[30], top = -1;
struct linked_list* head = NULL;
int printfromstack(int stack[]) {
cout<<"\nStack after Reversal::";
while(top>=0) {
cout<<stack[top--]<<" ";
}
}
int push(struct linked_list** head, int n) {
struct linked_list* newnode = (struct linked_list*)malloc(sizeof(struct linked_list));
newnode->data = n;
newnode->next = (*head);
(*head) = newnode;
}
int intostack(struct linked_list* head) {
cout<<"Linked list::";
while(head!=NULL) {
printf("%d ", head->data);
stack[++top] = head->data;
head = head->next;
}
}
int main(int argc, char const *argv[]) {
push(&head, 7);
push(&head, 20);
push(&head, 3);
push(&head, 40);
intostack(head);
printfromstack(stack);
return 0;
} উপরের কোডে দেখা গেছে, সমস্ত স্ট্রিং অপারেশন কোড retrieveChar()-এ বান্ডিল করা হয়েছে পদ্ধতি, পরে, কোন কলটি প্রোগ্রাম main() এক্সিকিউশনে পাস করা হয়।
আউটপুট
Linked list:: 40 3 20 7 Stack after Reversal::7 20 3 40