Nishant DAA 1.1
Nishant DAA 1.1
Experiment 1.1
Aim: : Analyze if stack Isempty, Isfull and if elements are present then return top element in
stacks using templates and also perform push and pop operation in stack.
Procedure/Algorithm:
Step1: Create stack.
Step2: Check underflow and overflow condition.
Step3: Increment top to store element in stack.
Step4: Decrement top after removing element form stack.
Step5: Check is stack empty or not.
Sample Code:
#include<iostream>
using namespace std;
class stack{
public:
int size;
int *arr;
int top;
stack(int size ){
this->size=size;
arr=new int[size];
top=-1;
}
void push(int element){
NishantBhardwaj UID: 21BCS7081
Course Name: DAA Lab Course Code: 21ITH-311/21CSH-311
if(top==size-1){
cout<<"Stack Overflow"<<endl;
}
top++;
arr[top]=element;
}
void pop(){
if(top==-1){
cout<<"Stack is empty"<<endl;
}
else if(top>=0){
top--;}
}
int peek() {
if(top>-1 && top<size){
return arr[top];
}
else{
cout<<"Stack is empty"<<endl;
return 0;}
}
bool isempty(){
if(top==-1){
return true;
}
else {
return false;
}
}
bool isfull(){
NishantBhardwaj UID: 21BCS7081
Course Name: DAA Lab Course Code: 21ITH-311/21CSH-311
if(top==size-1){
return true;
}
else{
return false;}
}
};
int main(){
stack st(5);
st.push(1);
st.push(2);
st.push(3);
st.push(4);
st.push(5);
cout<<"Nishant Bhardwaj"<<endl;
cout<<"21BCS7081"<<endl;
cout<<"Top element of the stack is "<<st.peek()<<endl;
cout<<"Is stack is full ? " <<st.isfull()<<endl;
cout<<"Is stack is empty ? "<<st.isempty()<<endl;
st.pop();
cout<<"After Pop operation"<<endl;
cout<<"Top element of the stack is "<<st.peek()<<endl;}
Observations/Outcome :
Time Complexity:
Stack work on LIFO( Last in first out). The time complexity of all stack operations is constant
i.e. O(1).