Implementing the Stack Algorithm/Data Structure
Solution
In this tutorial, we will learn how to implement a Stack Data Structure/Algorithm.
This data structure works on the LIFO technique, where LIFO stands for Last In First Out.
The element which was last inserted will be extracted at the first and so on.
Stack allows elements to be added and removed from one end only.
Using some of the OOP concepts to implement the Algorithm, we will use the likes of classes and functions.
What we will learn:
- How to implement the insert functionality
- How to implement the delete/remove functionality
- How to implement the display functionality
The code snippet below:
class StacksDs{ public: int stack[100], n=100, top=-1; void push(int val) { if(top>=n-1) cout<<"Stack Overflow"<<endl; else { top++; stack[top]=val; } } void pop() { if(top<=-1) cout<<"Stack Underflow"<<endl; else { cout<<"The popped element is "<< stack[top] <<endl; top--; } } void display() { if(top>=0) { cout<<"Stack elements are:"; for(int i=top; i>=0; i--) cout<<stack[i]<<" "; cout<<endl; } else cout<<"Stack is empty"; } void StackMenu(){ cout << "You are now in the Stacks" << endl; int ch, val; cout<<"1) Push in stack"<<endl; cout<<"2) Pop from stack"<<endl; cout<<"3) Display stack"<<endl; cout<<"4) Exit"<<endl; do { cout<<"Enter choice: "<<endl; cin>>ch; switch(ch) { case 1: { cout<<"Enter value to be pushed:"<<endl; cin>>val; push(val); break; } case 2: { pop(); break; } case 3: { display(); break; } case 4: { cout<<"Exit"<<endl; break; } default: { cout<<"Invalid Choice"<<endl; break; } } }while(ch!=4); } }; |
Answers ( 0 )