0% found this document useful (0 votes)
109 views3 pages

C Stack Implementation Guide

This document describes how to implement a stack data structure in C using a struct. The struct contains an array to store the stack elements and an integer to track the size. Functions are defined to initialize the stack, add/remove elements, and check the top element. An example main function demonstrates pushing/popping elements onto the stack and checking the top value.

Uploaded by

gdskumar
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
109 views3 pages

C Stack Implementation Guide

This document describes how to implement a stack data structure in C using a struct. The struct contains an array to store the stack elements and an integer to track the size. Functions are defined to initialize the stack, add/remove elements, and check the top element. An example main function demonstrates pushing/popping elements onto the stack and checking the top value.

Uploaded by

gdskumar
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Stack Implementation in C

#define STACK_MAX 100

struct Stack {
int data[STACK_MAX];
int size;
};
typedef struct Stack Stack;

void Stack_Init(Stack *S)


{
S->size = 0;
}

int Stack_Top(Stack *S)


{
if (S->size == 0) {
fprintf(stderr, "Error: stack
empty\n");
return -1;
}

return S->data[S->size-1];
}

void Stack_Push(Stack *S, int d)


{
if (S->size < STACK_MAX)
S->data[S->size++] = d;
else
fprintf(stderr, "Error: stack
full\n");
}

void Stack_Pop(Stack *S)


{
if (S->size == 0)
fprintf(stderr, "Error: stack
empty\n");
else
S->size--;
}

Using Stack Struct in C

void main()
{
Stack S;

Stack_Init(&S);

Stack_Push(&S, 30);
Stack_Push(&S, 40);
printf("Top: %d\n", Stack_Top(&S));

Stack_Pop(&S);
printf("Top: %d\n", Stack_Top(&S));

Stack_Pop(&S);
printf("Top: %d\n", Stack_Top(&S));
}

You might also like