Suraj-Ajjampur / DSA

0 stars 0 forks source link

Stack Basics #4

Open Suraj-Ajjampur opened 6 months ago

Suraj-Ajjampur commented 6 months ago

Structure of a stack

struct stack
{
int size;
int Top;
int *s;
};

Conditions

Empty

if(top ==-1)

Full

if(Top ==size-1)

Operations

Insert elements in stack

void push(stack *st){
//Check for full condition
if(st->top == st->size-1)
printf("Stack Overflow");
else{
st->s[t->top]=x;
st->top++;
}
}

Delete Elements from the stack

Check for Empty condition Delete an element from the stack decrement top pointer

int pop(stack *st)
{
int x= -1;
if(st->top == -1)
printf("Stack Underflow");
else
{
x= st->s[st->top];
st->top--;
}
return x;
}

Peek

Finding an element in the stack given the position

int peek(stack st, int pos)
{
  if(top-pos+1<0)
printf("Invalid Position");
else
x = st.s[st->top-pos+1];
return x;
}

StackTop

Finding the top most element in the stack

int stackTop(stack st)
{
if(st.top==-1)
return -1;
else return st.s[st.top];
}

Stack Empty

Check if stack is empty

bool stackEmpty(stack st){
if(st.top == -1)
return true;
else
return false;
}

Stack Full

Check if stack is full

bool stackFull(stack st){
if(st.top == st.size-1){
return true;
else return false;
}
Suraj-Ajjampur commented 6 months ago

Basic code adding with commit https://github.com/Suraj-Ajjampur/DSA/commit/a77203038b791a2ca671174a6fcec8d8bb25daa8