0% found this document useful (0 votes)
3 views

Stack Using Array

Uploaded by

Ayush Sharma
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Stack Using Array

Uploaded by

Ayush Sharma
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 2

#include <stdio.

h>
#include <stdlib.h>

#define MAX 100 // Maximum size of the stack

// Structure to represent a stack


struct Stack {
int arr[MAX]; // Array to store stack elements
int top; // Index of the top element
};

// Function to initialize the stack


void initStack(struct Stack* stack) {
stack->top = -1; // Set top to -1 indicating an empty stack
}

// Function to check if the stack is empty


int isEmpty(struct Stack* stack) {
return stack->top == -1;
}

// Function to check if the stack is full


int isFull(struct Stack* stack) {
return stack->top == MAX - 1;
}

// Function to push an element onto the stack


void push(struct Stack* stack, int data) {
if (isFull(stack)) {
printf("Stack overflow! Cannot push %d\n", data);
return;
}
stack->arr[++stack->top] = data;
printf("%d pushed to stack\n", data);
}

// Function to pop an element from the stack


int pop(struct Stack* stack) {
if (isEmpty(stack)) {
printf("Stack underflow! Cannot pop\n");
return -1;
}
return stack->arr[stack->top--];
}

// Function to peek the top element of the stack


int peek(struct Stack* stack) {
if (isEmpty(stack)) {
printf("Stack is empty\n");
return -1;
}
return stack->arr[stack->top];
}

// Driver code to test the stack implementation


int main() {
struct Stack stack;
initStack(&stack);
push(&stack, 10);
push(&stack, 20);
push(&stack, 30);

printf("%d popped from stack\n", pop(&stack));


printf("Top element is %d\n", peek(&stack));

return 0;
}

You might also like