Home Data Structures Stack Data Structure Tutorial and Implementation

# Stack Data Structure Tutorial and Implementation

The stack is a Data Structure that supports insertion and deletion of elements in a particular order, i.e, LIFO (Last In First Out). Whenever any element is inserted it goes to the top of the stack and the element which is inserted at the last (element at the top of the stack) will be removed at first.

Basic Stack Operation:

PUSH: Push operation is used to insert an element into the stack data structure. It pushes/inserts an element at the top of the stack. If the stack is full, it will return Stack Overflow. If expects an element to be inserted as an input parameter.

```Algorithm:
push(int element):
if(tos == max_size):
printf("stack overflow");
else:
tos++;
stack[tos] = element;
```

POP: Pop operation is used to delete an element from the top of the stack. If the stack is empty, it will return stack underflow.

```Algorithm:
pop():
if(top==-1):
printf("Stack Underflow")
else:
stack[tos] == 0;
tos--;```

Note: tos is a variable that points to the top of the stack.

Time Complexity Of Stack Operation

1. Push Operation: O(1)
2. Pop Operation: O(1)
3. Search an Element: O(N)

Implementation of Stack in CPP

```#include <bits/stdc++.h>
using namespace std;

int max_size = 7;
int tos=-1;
vector<int> stack_ds(max_size);

int push(int element){
if(tos == max_size)
cout<<"Stack Overflow"<<endl;
else
stack_ds[++tos] = element;

return 0;
}

int pop(){
if(tos == -1)
cout<<"Stack Underflow"<<endl;
else
stack_ds[tos--]=0;

return 0;
}

int display_stack(){
if(tos == -1)
cout<<"Stack is empty"<<endl;
else{
cout<<"Stack content is:"<<endl;
for(int i=0;i<=tos;i++)
cout<<stack_ds[i]<<" ";

cout<<endl;
}
return 0;
}

int main(){

push(1);
push(5);
push(7);
push(9);
push(10);
push(12);
push(15);
display_stack();
pop();
pop();
display_stack();

return 0;
}
```
##### Output:
```Stack content is:
1 5 7 9 10 12 15
Stack content is:
1 5 7 9 10```

#### 1 COMMENT

1. hemant

bro this is easy++