Porgram to find second largest element in stack.

program:-

#include<stdio.h>
struct stack
{
int top;
int capacity;
int *array;
};
struct stack* creatstack(int cap)
{
struct stack *stack;
stack=(struct stack*)malloc(sizeof(struct stack));
stack->top=-1;
stack->capacity=cap;
stack->array=(int *)malloc(sizeof(int)*stack->capacity);
return(stack);
}
int isfull(struct stack* stack)
{
if(stack->top==stack->capacity1)
return(0);
else
return(1);
}
int isempty(struct stack *stack)
{
if(stack->top==-1)
return(0);
else
return(1);
}
void push(struct stack *stack,int val)
{
if(isfull(stack))
{
stack->top++;
stack->array[stack->top]=val;
}
else
printf(“Stack is Full”);
}
int pop(struct stack *stack)
{
int item;
if(isempty(stack))
{
item=stack->array[stack->top];
stack->top–;
}
else
return(-1);
}
void main()
{
int n,val,second_max=0,max,newtop;
struct stack *stack;
clrscr();
printf(“Enter number of Element of in stack”);
scanf(“%d”,&n);
stack=creatstack(n);
while(isfull(stack))
{
system(“cls”); // here you can also use clrscr();
printf(“Enter Element of stack”);
scanf(“%d”,&val);
push(stack,val);
}
newtop=stack->top;
max=pop(stack);
while(isempty(stack))
{
val=pop(stack);
if(max<val)
max=val;
}
printf(“nGreatest Element is %dn”,max);
stack->top=newtop;
while(isempty(stack))
{
val=pop(stack);
if(second_max<val&&val<max)
second_max=val;
}
printf(“Second Greatest Element is %d”,second_max);
getch();
}


Leave a Reply

Your email address will not be published.