C-Algorithms-Data_Structures/Dynamic Stack in C/main.c

103 lines
1.9 KiB
C
Raw Normal View History

2024-07-04 23:12:10 +03:00
#include <stdio.h>
2024-07-06 20:56:24 +03:00
#include <stdlib.h>
2024-07-04 23:12:10 +03:00
const int STACK_SIZE = 10;
typedef struct Stack Stack;
struct Stack {
int top;
int* elements;
int size;
};
Stack new() {
Stack stack;
stack.top = -1;
2024-07-06 20:56:24 +03:00
stack.size = 0;
stack.elements = (int*)malloc(0);
2024-07-04 23:12:10 +03:00
return stack;
}
int push(Stack* stack, int element) {
int* new_space_ptr = (int*)realloc(stack->elements, (stack->size+1)*sizeof(int));
2024-07-06 20:56:24 +03:00
if (!new_space_ptr) {
2024-07-04 23:12:10 +03:00
return -1;
}
2024-07-06 20:56:24 +03:00
stack->size++;
2024-07-04 23:12:10 +03:00
stack->elements[stack->top+1] = element;
stack->top++;
return 0;
}
int* pop(Stack* stack) {
if (stack->top == -1) {
return NULL;
}
int* element = &stack->elements[stack->top];
int* new_space_ptr = (int*)realloc(stack->elements, (stack->size-1) * sizeof(int));
2024-07-06 20:56:24 +03:00
stack->size--;
2024-07-04 23:12:10 +03:00
stack->top--;
return element;
}
int* get(Stack* stack, int index) {
if (index < 0 || index > stack->top) {
return NULL;
}
return &stack->elements[index];
}
int search(Stack* stack, int element) {
int current_index = 0;
while (current_index <= stack->top) {
if (stack->elements[current_index] == element) {
return current_index;
}
current_index ++;
}
return -1;
}
int main() {
printf("Hello World\n");
Stack stack = new();
push(&stack, 123);
push(&stack, 5);
int* value_ptr = get(&stack, 0);
if (!value_ptr) {
2024-07-06 23:01:34 +03:00
printf("Invalid Index\n");
2024-07-04 23:12:10 +03:00
return -1;
}
printf("%d\n", *value_ptr);
int searched = search(&stack, 5);
if (searched== -1) {
printf("Not Found\n");
return -1;
}
printf("Index of Searched Value = %d\n", searched);
int* popped = pop(&stack);
if(!popped) {
2024-07-06 23:01:34 +03:00
printf("Couldn't Pop");
2024-07-04 23:12:10 +03:00
return -1;
}
printf("%d\n", *popped);
int searched_again = search(&stack, 5);
if (searched_again== -1) {
printf("Not Found\n");
return -1;
}
}