C Stack Implementation Guide
Here is a basic example of implementing a stack in C language.
#include <stdio.h>
#include <stdlib.h>
#define MAX_SIZE 100
typedef struct {
int data[MAX_SIZE];
int top;
} Stack;
void initStack(Stack *s) {
s->top = -1;
}
int isEmpty(Stack *s) {
return s->top == -1;
}
int isFull(Stack *s) {
return s->top == MAX_SIZE - 1;
}
void push(Stack *s, int value) {
if (isFull(s)) {
printf("Stack is full\n");
return;
}
s->top++;
s->data[s->top] = value;
}
int pop(Stack *s) {
if (isEmpty(s)) {
printf("Stack is empty\n");
return -1;
}
int value = s->data[s->top];
s->top--;
return value;
}
int peek(Stack *s) {
if (isEmpty(s)) {
printf("Stack is empty\n");
return -1;
}
return s->data[s->top];
}
int main() {
Stack stack;
initStack(&stack);
push(&stack, 10);
push(&stack, 20);
push(&stack, 30);
printf("Top element: %d\n", peek(&stack));
printf("Popped element: %d\n", pop(&stack));
printf("Popped element: %d\n", pop(&stack));
printf("Popped element: %d\n", pop(&stack));
printf("Is stack empty: %s\n", isEmpty(&stack) ? "true" : "false");
return 0;
}
This code defines a basic sequential stack data structure, including operations for initializing the stack, checking if it is empty or full, pushing elements onto the stack, popping elements from the stack, and getting the top element of the stack. In the main function, the stack is initialized, elements are pushed and popped, and some information is printed.
You can modify and extend the code according to your own needs.