-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathStack_Char.c
42 lines (34 loc) · 1010 Bytes
/
Stack_Char.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#include <stdio.h>
#include <stdlib.h>
#define MagicFactor 1.5
// Notice that the stack is nothing but a "List" that removes and adds from the last position
// i.e, Last In First Out (LIFO)
typedef struct {
char *data;
size_t size;
size_t capacity;
} Stack;
// Our main add() function to add element in the "stack"
void push(Stack *stack, char value) {
if (stack->size == stack->capacity) {
stack->capacity *= MagicFactor;
char *temp = realloc(stack->data, stack->capacity * sizeof(char));
if (temp == NULL) {
printf("Error: Could not allocate memory\n");
exit(1);
}
stack->data = temp;
}
stack->data[stack->size] = value;
stack->size++;
}
// Our remove() function to remove elements from the last position
int pop(Stack* stack) {
if (stack->size == 0) {
return -1;
} else {
char last_element = stack->data[stack->size - 1];
stack->size--;
return last_element;
}
}