### Stack Data Structure | Introduction and Basic Operations

- Stack is linear abstract data structure.
- We can done Addition or deletion of elements only at the one open end called the top of the stack.
- The elements follow “Last In First Out”, typically called
**LIFO.** - Inserting elements into the stack is called
**Push**operation. And deleting elements from the stack is called**pop**operation. - When Stack is in
**overflow**state, then the Push operation is rejected. And if it is in**underflow**state then Pop operation is rejected.

### Stack as an array

The array are static data structures, space required for them must be predetermined i.e. we must know how many total elements will be existing before compilation. Therefore, creation of a stack as array involves determining the number of elements beforehand.

**Insertion in a stack as an array (push operation)**

When we insert new element it will be inserted from the top. **Top** contains the reference of the current most element which is inserted into the stack.

If the Stack is full because top is equal to size of the array (as in above fig.) then no new element is inserted and as a result STACK-FULL condition occurs. This condition is also called an OVERFLOW.

**Algorithm :- **

Let S is a Stack of Size =100 elements, and top is an integer to hold the index of the last inserted element into the stack. Initially Top :=-1 Step 1: PROCEDURE PUSH(VALUE) Step 2: IF TOP := SIZE-1 THEN Step 3: DISPLAY “STACK OVERFLOW” Step 4: EXIT PUSH Step 5: END IF Step 6: TOP := TOP+1 //Increment the top of the stack S by 1 Step 7: S[TOP] := V //Assign the element at the top position of the stack Step 8: END PROCEDURE PUSH

**Deletion in stack as an array (pop operation)**

Popping i.e. deletion of an element is done at top most position from a stack i.e. the element is deleted first which is place on the top and stored in the top variable is deleted first.

In case, if stack is empty i.e. top is equal to -1 and hence trying to delete an element from an empty stack, then this condition is called an UNDERFLOW.

**Algorithm :-**

Step 1: PROCEDURE POP() Step 2: IF S.TOP =-1 THEN Step 3: DISPLAY “STACK UNDERFLOW” Step 4: EXIT POP Step 5: END IF Step 6: V := S[TOP] Step 7: TOP := TOP-1 Step 8: RETURN V Step 9: END PROCEDURE POP

### Practical examples :-

- Undo operation
- Browser back operation
- Conversion decimal to binary

**Code :-**

#include<iostream> using namespace std; #define SIZE 10 class stack{ private: int item[SIZE]; int top; public : stack(){ top=-1; } void push(int value){ if(top==SIZE-1){ cout<<"Stack Overflown"; } top++; item[top]=value; } int pop(){ if(top==-1){ cout<<"Stack Underflown"; return -1; } int value; value = item[top]; top--; return value; } }; int main(){ stack s; s.push(10); s.push(20); s.push(30); cout<<s.pop()<<endl; ///Delete and display 30 cout<<s.pop()<<endl; ///Delete and display 30 return 0; }

CommentsNo comment yet.