स्टैक एक रैखिक डेटा संरचना है जिसमें ऑपरेशन एक विशेष क्रम में किए जाते हैं। यह क्रम FILO (फर्स्ट इन फर्स्ट आउट) या LIFO (लास्ट इन फर्स्ट आउट) हो सकता है।
एल्गोरिदम
Begin
स्टैक वेक्टर घोषित करें।
पसंद के अनुसार इनपुट लें।
स्विच ऑपरेशन के भीतर फंक्शन कॉल करें:
s.size() = स्टैक का आकार लौटाता है।
s.push() = स्टैक में तत्व डालने के लिए उपयोग किया जाता है।
s.pop() = स्टैक से मान बाहर निकालने के लिए।
s.top() = स्टैक के शीर्ष तत्व का संदर्भ लौटाता है।
End.
उदाहरण कोड
#include <iostream>
#include <stack>
#include <string>
#include <cstdlib>
using namespace std;
int main() {
stack<int> s;
int c, i;
while (1) {
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 >> c;
switch(c) {
case 1:
cout << "Size of the stack: ";
cout << s.size() << endl;
break;
case 2:
cout << "Enter value to be inserted: ";
cin >> i;
s.push(i);
break;
case 3:
i = s.top();
if (!s.empty()) {
s.pop();
cout << i << " Deleted" << endl;
} else {
cout << "Stack is Empty" << endl;
}
break;
case 4:
cout << "Top Element of the Stack: ";
cout << s.top() << endl;
break;
case 5:
exit(1);
break;
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