// 1• WAP to implement a stack which will support three additional operations in addition to push and pop by modifying LA 1.
// a) peekLowestElement - return the lowest element in the stack without removing it from the stack
// b) peekHighestElement - return the highest element in the stack without removing it from the stack
// c) peekMiddleElement - return the (size/2+1)th lowest element in the stack without removing it from the stack.
#include <stdio.h>
#include <stdlib.h>
struct stack
{
int size;
int top;
int *arr;
};
int isEmpty(struct stack *ptr)
{
if (ptr->top == -1)
{
return 1;
}
else
{
return 0;
}
}
int isFull(struct stack *ptr)
{
if (ptr->top == ptr->size - 1)
{
return 1;
}
else
{
return 0;
}
}
void push(struct stack *ptr, int val)
{
if (isFull(ptr))
{
printf("Stack Overflow! Cannot push %d to the stack\n", val);
}
else
{
ptr->top++;
ptr->arr[ptr->top] = val;
}
}
int pop(struct stack *ptr)
{
if (isEmpty(ptr))
{
printf("Stack Underflow! Cannot pop from the stack\n");
return -1;
}
else
{
int val = ptr->arr[ptr->top];
ptr->top--;
return val;
}
}
int peekHighestElement(struct stack *ptr)
{
// return ptr->arr[ptr->top];
static int max = 0;
while (!isEmpty(ptr))
{
int x = pop(ptr);
if (x > max)
{
max = x;
}
int i = peekHighestElement(ptr);
push(ptr, x);
return max;
}
}
int peekLowestElement(struct stack *ptr)
{
/*
// int x = pop(ptr);
// if (isEmpty(ptr))
// {
// push(ptr, x);
// return x;
// }
// int i = peekLowestElement(ptr);
// push(ptr, x);
// return i;
*/
static int min = INT_MAX;
while (!isEmpty(ptr))
{
int x = pop(ptr);
if (x < min)
{
min = x;
}
int i = peekLowestElement(ptr);
push(ptr, x);
return min;
}
}
int peekMiddleElement(struct stack *ptr)
{
int m = (ptr->top / 2) + 1;
static int k = 0;
int x = pop(ptr);
if (m == k)
{
push(ptr, x);
return x;
}
else
{
k++;
}
int i = peekMiddleElement(ptr);
push(ptr, x);
return i;
}
void display(struct stack *ptr)
{
printf("elements : ");
int k = ptr->top;
while (k != -1)
{
printf("%d ", ptr->arr[k]);
k--;
}
}
int main()
{
int c, p;
struct stack *sp = (struct stack *)malloc(sizeof(struct stack));
printf("enter the size of stack : ");
scanf("%d", &p);
sp->size = p;
sp->top = -1;
sp->arr = (int *)malloc(sp->size * sizeof(int));
printf("Stack has been created successfully\n");
push(sp, 11);
push(sp, 5);
push(sp, 8);
push(sp, 10);
push(sp, 12);
push(sp, 7);
printf("HighestElement : %d\n", peekHighestElement(sp));
printf("LowestElement : %d\n", peekLowestElement(sp));
printf("MiddleElement : %d\n", peekMiddleElement(sp));
display(sp);
return 0;
}