If suppose i want to implement a stack in c using arrrays is it better to do it via making a structure or class for storing the location of head and stuff like that or should you implement in more of a hard code style like this -
#include <iostream>
using namespace std;
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";
}
int main() {
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;
}
}
}while(ch!=4);
return 0;
}
Im just trying to know what is a more accepted method.
CodePudding user response:
The approach you've taken here using global variables is fine for a simple implementation, but it has a major drawback in most real-world applications: it's not reusable.
What if you need two stacks in your program? That would require creating a second set of global variables and a second set of functions to act on them.
That is the problem that using a class solves. If you wrap all of your stack's state in a class then you can create a single set of functions that can operate on any object of that class. Then creating a second stack is very simple.
Of course, for most real world applications you shouldn't implement your own stack anyway. Just use std::stack
unless you have a very compelling reason not to. But that still supports the same conclusion. Because std::stack
is a self-contained, reusable class any program can use it without having to re-implement their own stack logic (possibly multiple times).