Implement a stack using C such that the stack does not allow insertion of duplicate numbers. (Push and Pop operations)

Leave a Comment
#include<stdio.h>
#include<stdlib.h>

#include<conio.h>


int a[100];
int top=-1;


int item,n;
int isempty()
{
if(top==-1)
return 1;
else
return 0;
}
int isfull()
{
if(top==(n-1))
return 1;
else
return 0;
}


void push(int item)
{
int flag=0,i;
for(i=0;i<=top;i++)
{
if(a[i]==item)
{
flag=1;
break;
}
}

if(isfull()==1)
{
printf("\nStack overflowed!!!");
}
else{
if(flag==0)
{
top++;
a[top]=item;
}
else
printf("\nThe element is present previously in the stack, you have to reenter the element!!!!");
}
}


int pop()
{
if(isempty()==1)
{
printf("\nThe stcks is empty!!!");

}
else{
int item=a[top];
top--;
return item;
}
}
int seek_peak()
{
return a[top];
}


int main()
{
printf("\nEnter the max. limit for the stack:");
scanf("%d",&n);
int o,op;
while(o!=0)
{
printf("\nENTER YOUR OPTION!!\n");
printf("\nEnter 1 for PUSH");
printf("\nEnter 2 for POP");
printf("\nEnter 3 for checking the stack is empty or not!!!!!");
printf("\nEnter 4 for checking the stack is full or not!!!!");
printf("\nEnter 5 for seeking the peak element");
printf("\nEnter 0 for exit!!");
scanf("%d",&o);
switch(o)
{
case 1:{
printf("\nEnter the element to push in the stack:");
scanf("%d",&item);
push(item);
break;
}
case 2:{ item=pop();

printf("\nthe popped element is %d", item);
break;
}
case 3:{ if(isempty()==1)
printf("\nThe stack is empty!!");
else
printf("\nThe stack is not empty!!!!");
break;
}
case 4:{
if(isfull()==1)
printf("\nThe stack is full!!!");
else
printf("\nThe stack is not full!!!");
break;
}
case 5: { printf("\nThe peak element is:%d",seek_peak());
break;
}
default:printf("\nU have entered a wrong choice!!!");
}
}
getche();
}

0 comments: