Find min in stack by R4R Team

What is Stack ?
Stack is a linear data structure which follows a particular order in which the operations are performed.
The order may be LIFO(Last In First Out) or FILO(First In Last Out).

How find minimum element in stack:
Function:

void minimum()
{
struct stack *ptr=top;
int ans=top->data;
while(ptr!=NULL)
{
if(ptr->data< ans)
ans=ptr->data;
ptr=ptr->back;
}
printf("Minimum is %d",ans);
}



program-

#include< stdio.h>
#include< conio.h>
#include< alloc.h>
struct stack
{
int data;
struct stack *back;
};
struct stack *top;

void create()
{
char ch;
struct stack *ptr,*cpt;
printf("Enter Number\n");
cpt=(struct node*)malloc(sizeof(struct stack));
scanf("%d",&cpt->data);
cpt->back=NULL;
do
{
printf("Enter Number\n");
ptr=(struct stack*)malloc(sizeof(struct stack));
scanf("%d",&ptr->data);
ptr->back=cpt;
cpt=ptr;
printf("Continue(y/n)?\n");
ch=getch();
}while(ch=='y');
top=cpt;
}

void traverse()
{
struct stack *ptr=top;
printf("Stack is :\n");
while(ptr!=NULL)
{
printf("%d ",ptr->data);
ptr=ptr->back;
}
}

void minimum()
{
struct stack *ptr=top;
int ans=top->data;
while(ptr!=NULL)
{
if(ptr->data< ans)
ans=ptr->data;
ptr=ptr->back;
}
printf("Minimum is %d",ans);
}

void main()
{
clrscr();
create();
traverse();
minimum();
getch();
}


output-

Enter Number
3
Enter Number
4
Continue(y/n)?
Enter Number
7
Continue(y/n)?
Enter Number
1
Continue(y/n)?
Stack is :
1 7 4 3
Minimum is 1

-In this program, we have a three function create(), traverse() and pop()
- create() function are used to create a stack
- traverse() function are used to traverse the stack
- minimum() function are used to find the minimum element of the stack.




Leave a Comment:
Search
Categories
R4R Team
R4Rin Top Tutorials are Core Java,Hibernate ,Spring,Sturts.The content on R4R.in website is done by expert team not only with the help of books but along with the strong professional knowledge in all context like coding,designing, marketing,etc!