You are on page 1of 2

//Implementation of a stack using an array in C

#include <stdio.h>
#define MAX_SIZE 100

struct Stack
{
int items[MAX_SIZE];
int top;
};

void initialize(struct Stack* stack)


{
stack->top=-1;
}

int isFull(struct Stack* stack)


{
return stack->top==MAX_SIZE-1;
}

int isEmpty(struct Stack* stack)


{
return stack->top==-1;
}

void push(struct Stack* stack,int item)


{
if(isFull(stack))
{
printf("Stack is full. Cannot push element.\n");
}
else
{
stack->top++;
stack->items[stack->top]=item;
}
}

int pop(struct Stack* stack)


{
if(isEmpty(stack))
{
printf("Stack is empty. Cannot pop element.\n");
return -1;
}
else
{
int item=stack->items[stack->top];
stack->top--;
return item;
}
}

int peek(struct Stack* stack)


{
if(isEmpty(stack))
{
printf("Stack is empty.\n");
return -1;
}
else
{
return stack->items[stack->top];
}
}

int main()
{
struct Stack stack;
initialize(&stack);
int n,val;
scanf("%d",&n);
while(n--)
{
scanf("%d",&val);
push(&stack,val);
}
printf("Top element: %d\n",peek(&stack));
printf("Elements: ");
while (!isEmpty(&stack))
{
printf("%d ",pop(&stack));
}
return 0;
}

You might also like