C_Algorithms 2.0.0
Documentation
Loading...
Searching...
No Matches
stack.c
Go to the documentation of this file.
1#include <stdio.h>
2#include <stdlib.h>
3
4#include "stack.h"
5
6
7
14mystack_t *CreateStack(uint32_t capacity)
15{
16 mystack_t *stack = (mystack_t *)malloc(sizeof(mystack_t));
17
18 if (stack == NULL)
19 return NULL;
20
21 size_t data_size = capacity * sizeof(stack_value_t);
22 stack_value_t *data = (stack_value_t *)malloc(data_size);
23
24 if (data == NULL)
25 {
26 free(stack);
27 return NULL;
28 }
29
30 stack->capacity = capacity;
31 stack->size = 0u;
32 stack->data = data;
33
34 return stack;
35}
36
44{
45 if (stack != NULL)
46 {
47 if (stack->data != NULL)
48 {
49 free(stack->data);
50 }
51 free(stack);
52 }
53 return NULL;
54}
55
64{
65 return (stack->size == 0u);
66}
67
76{
77 return (stack->size == stack->capacity);
78}
79
86{
87 if (StackIsFull(stack))
88 {
89 return;
90 }
91
92 stack->data[stack->size] = value;
93 stack->size++;
94}
95
103{
104 if (StackIsEmpty(stack))
105 return STACK_NO_VALUE;
106 stack->size--;
107 return stack->data[stack->size];
108}
109
110
118{
119 if (StackIsEmpty(stack))
120 return STACK_NO_VALUE;
121 return stack->data[stack->size - 1];
122}
123
130{
131 if (stack == NULL)
132 return;
133
134 printf(
135 "The stack contains %u elements with a capacity of %u.\n",
136 stack->size,
138 );
139
140 for (int32_t i = 0; i < stack->size; i++)
141 {
142 printf("Index: %d, Value %f\n", i, stack->data[i]);
143 }
144}
145
146
147/*<-- SIMPLE CALL TO NOT CLUTTER THE MAIN.C -->*/
148void Stack()
149{
150 uint32_t capacity = 4u;
151 mystack_t *stack = CreateStack(capacity);
152 PushStack(stack, 2.0f);
153 PushStack(stack, 3.0f);
156}
stack_value_t TopStack(mystack_t *stack)
Return the top object of the stack.
Definition stack.c:117
void PrintStack(mystack_t *stack)
Print the whole stack.
Definition stack.c:129
bool StackIsFull(mystack_t *stack)
Check if the Stack object is full.
Definition stack.c:75
mystack_t * CreateStack(uint32_t capacity)
Create a Stack object.
Definition stack.c:14
bool StackIsEmpty(mystack_t *stack)
Check if the Stack object is empty.
Definition stack.c:63
void Stack()
Definition stack.c:148
mystack_t * FreeStack(mystack_t *stack)
Free the memory of a given Stack object.
Definition stack.c:43
void PushStack(mystack_t *stack, stack_value_t value)
Push a new object to the stack.
Definition stack.c:85
stack_value_t PopStack(mystack_t *stack)
Pop the object on top of the stack.
Definition stack.c:102
#define STACK_NO_VALUE
Definition stack.h:10
float stack_value_t
Definition stack.h:9
Definition stack.h:13
uint32_t capacity
Definition stack.h:15
uint32_t size
Definition stack.h:14
stack_value_t * data
Definition stack.h:16