unknown Interview Question
PersonnelsCountry: India
The basic idea behind this is whenever u add some element into the stack all you have to do is store the minimum element of the stack in the top most element of the stack. So the next time you insert you can compare the value of the node that is being inserted and the minimum node that is at the top of the stack and decide the new minimum from this information.
(nobrainer .co .cc)
This algo is to find min & max value in the stack using linked list.
the idea is create the linked list by adding new nodes at top(first), after forming the list find the minimum&maximum value in it.
this linked list uses stack procedure to create.
To find the min value,
int find_min(struct node *p)
{
p=top;
int mn=p->data;
while(p!=NULL)
{
if(mn > p->data)
{
mn=p->data;
p=p->link;
}
else
p=p->link;
}
return mn;
}
To find the max value
int find_max(struct node *q)
{
q=top;
int mx=q->data;
while(q!=NULL)
{
if(mx < q->data)
{
mx=q->data;
q=q->link;
}
else
q=q->link;
}
return mx;
}
The basic idea behind this is whenever u add some element into the stack all you have to do is store the minimum element of the stack in the top most element of the stack. So the next time you insert you can compare the value of the node that is being inserted and the minimum node that is at the top of the stack and decide the new minimum from this information.
- anony February 14, 2012