The primary advantage of using an array for implementing a stack is that it is more time-efficient than linked list implementation of the stack, which takes extra time in allocating pointers of nodes whenever there is a change in the size of the stack. All the operations in case of an array-based implementation of a stack are performed in O (1) time.
Operations performed are :
-
Push: This operation adds an item to the stack; it will throw an exception if the stack’s capacity is full.
-
Pop: This removes the last inserted element from a stack that is removed in reverse order of their insertion; it will throw an underflow exception if the given stack is empty.
-
Peek: This operation returns the topmost element of the stack.
-
IsEmpty: Checks if a stack is empty or not. Returns true if the given stack is empty; otherwise, it returns false.
-
IsStackFull: Checks if a stack is full or not. Returns true if the given stack is full; otherwise, it returns false.
PSUEDO CODE:-
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";
}