Files
C/data_structures/stack/stack_linked_list/stack.c

89 lines
1.4 KiB
C
Raw Normal View History

#include "stack.h"
2019-07-01 18:06:21 -07:00
#include <assert.h>
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
2019-07-01 18:06:21 -07:00
#define T Stack_T
typedef struct elem
{
2019-07-01 18:06:21 -07:00
void *val;
2019-07-02 16:02:55 -07:00
struct elem *next;
2019-07-01 18:06:21 -07:00
} elem_t;
struct T
{
2019-07-01 18:06:21 -07:00
int count;
2019-07-02 16:02:55 -07:00
elem_t *head;
2019-07-01 18:06:21 -07:00
};
/* Initial stack */
T Stack_init(void)
{
2019-07-01 18:06:21 -07:00
T stack;
stack = (T)malloc(sizeof(T));
2019-07-02 16:02:55 -07:00
stack->count = 0;
stack->head = NULL;
return stack;
2019-07-01 18:06:21 -07:00
}
/* Check empty stack*/
int Stack_empty(T stack)
{
2019-07-01 18:06:21 -07:00
assert(stack);
2019-07-02 16:02:55 -07:00
return stack->count == 0;
2019-07-01 18:06:21 -07:00
}
/* Return size of the stack */
int Stack_size(T stack)
{
2019-07-01 18:06:21 -07:00
assert(stack);
2019-07-02 16:02:55 -07:00
return stack->count;
2019-07-01 18:06:21 -07:00
}
/* Push an element into the stack */
void Stack_push(T stack, void *val)
{
2019-07-01 18:06:21 -07:00
elem_t *t;
2019-07-02 16:02:55 -07:00
assert(stack);
t = (elem_t *)malloc(sizeof(elem_t));
2019-07-02 16:02:55 -07:00
t->val = val;
2019-07-01 18:06:21 -07:00
t->next = stack->head;
2019-07-02 16:02:55 -07:00
stack->head = t;
stack->count++;
2019-07-01 18:06:21 -07:00
}
/* Pop an element out of the stack */
void *Stack_pop(T stack)
{
2019-07-01 18:06:21 -07:00
void *val;
2019-07-02 16:02:55 -07:00
elem_t *t;
2019-07-01 18:06:21 -07:00
2019-07-02 16:02:55 -07:00
assert(stack);
assert(stack->count > 0);
t = stack->head;
stack->head = t->next;
2019-07-01 18:06:21 -07:00
stack->count--;
2019-07-02 16:02:55 -07:00
val = t->val;
free(t);
return val;
2019-07-01 18:06:21 -07:00
}
/* Print all elements in the stack */
void Stack_print(Stack_T stack)
{
2019-07-01 18:06:21 -07:00
assert(stack);
int i, size = Stack_size(stack);
2019-07-02 16:02:55 -07:00
elem_t *current_elem = stack->head;
printf("Stack [Top --- Bottom]: ");
for (i = 0; i < size; ++i)
{
2019-07-02 16:02:55 -07:00
printf("%p ", (int *)current_elem->val);
current_elem = current_elem->next;
}
printf("\n");
2019-07-01 18:06:21 -07:00
}