কম্পিউটার টিউটোরিয়াল

C++ STL-এ Stack বাস্তবায়ন: LIFO ডেটা স্ট্রাকচার

Stack একটি লিনিয়ার ডেটা স্ট্রাকচার যা নির্দিষ্ট ক্রমে অপারেশন সম্পাদন করে। এটি LIFO (Last In First Out) বা FILO (First In Last Out) nguyênনীতি মেনে চলে — অর্থাৎ, সবশেষে যোগ করা উপাদানটি সবচেয়ে প্রথম বের হয়।

এলগরিদম

শুরু
  স্ট্যাক ভেক্টর ঘোষণা করুন
  ইউজারের পছন্দ অনুযায়ী ইনপুট নিন
  সুইচ অপারেশনে ফাংশন কল করুন:
    s.size()  = স্ট্যাকের আকার রিটার্ন করে
    s.push()  = স্ট্যাকে উপাদান যোগ করে
    s.pop()   = স্ট্যাক থেকে উপাদান বের করে
    s.top()   = স্ট্যাকের শীর্ষ উপাদান রিটার্ন করে
শেষ

উদাহরণ কোড: ইন্টারেক্টিভ স্ট্যাক প্রোগ্রাম

#include <iostream>
#include <stack>
#include <string>
#include <cstdlib>
using namespace std;

int main() {
    stack<int> s;
    int choice, value;

    while (true) {
        cout << "1. Size of the Stack" << endl;
        cout << "2. Insert Element into the Stack" << endl;
        cout << "3. Delete Element from the Stack" << endl;
        cout << "4. Top Element of the Stack" << endl;
        cout << "5. Exit" << endl;
        cout << "Enter your Choice: ";
        cin >> choice;

        switch (choice) {
            case 1:
                cout << "Size of the stack: " << s.size() << endl;
                break;
            case 2:
                cout << "Enter value to be inserted: ";
                cin >> value;
                s.push(value);
                break;
            case 3:
                if (!s.empty()) {
                    value = s.top();
                    s.pop();
                    cout << value << " Deleted" << endl;
                } else {
                    cout << "Stack is Empty" << endl;
                }
                break;
            case 4:
                if (!s.empty())
                    cout << "Top Element of the Stack: " << s.top() << endl;
                else
                    cout << "Stack is Empty" << endl;
                break;
            case 5:
                exit(0);
            default:
                cout << "Wrong Choice" << endl;
        }
    }
    return 0;
}

নমুনা আউটপুট

1. Size of the Stack
2. Insert Element into the Stack
3. Delete Element from the Stack
4. Top Element of the Stack
5. Exit
Enter your Choice: 1
Size of the stack: 0
...
Enter your Choice: 2
Enter value to be inserted: 1
...
Enter your Choice: 1
Size of the stack: 5
Enter your Choice: 3
4 Deleted
Enter your Choice: 4
Top Element of the Stack: 10
Enter your Choice: 5
Exit code: 1

গুরুত্বপূর্ণ নোট: স্ট্যাকে pop() কল করার আগে সবসময় empty() চেক করা উচিত, অন্যথায় অন্ডারফ্লো হতে পারে। উপরের কোডে এই সুরক্ষা যোগ করা হয়েছে।

  1. C++ STL-এ Set Union বাস্তবায়ন: দুটি সেটের ইউনিয়ন

  2. C++ STL-এ Set Symmetric Difference বাস্তবায়ন

  3. C++ STL-এ Set Intersection বাস্তবায়ন: দুটি সেটের অন্তঃসেট

  4. C++ STL-এ Set Difference বাস্তবায়ন: সেট বিয়োগ