Skip to content

Instantly share code, notes, and snippets.

@mbelicki
Forked from kgabis/stack.c
Created September 14, 2011 16:33
Show Gist options
  • Save mbelicki/1217032 to your computer and use it in GitHub Desktop.
Save mbelicki/1217032 to your computer and use it in GitHub Desktop.
Linked stack in C
#include "..\Header\stack.h"
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
void stackpush(Stack ** stack, int value)
{
assert(stack != NULL);
/* perhaps there is way to do it without this if ... else */
if (*stack == NULL)
{
*stack = (Stack *)malloc(sizeof(Stack));
assert(*stack != NULL); /* TODO : allocation handling! */
(*stack)->value = value;
(*stack)->lower = NULL;
return;
}
else
{
Stack *new_node = (Stack *)malloc(sizeof(Stack));
assert(new_node != NULL); /* TODO : allocation handling! */
new_node->lower = *stack;
new_node->value = value;
*stack = new_node;
return;
}
}
int stackpop(Stack ** stack)
{
assert(stack != NULL); /* here it might be wise to do NULL handling */
Stack *new_top = stack->lower;
int removed_value = (*stack)->value;
free(*stack);
*stack = new_top;
return remove_value;
}
void stackdispose(Stack * stack)
{
while(stack != NULL)
stackpop(&stack);
}
typedef struct node_t
{
int value;
struct node_t * lower;
} Node;
typedef node_t Stack; /* yes, */
void stackinit(Stack*);
void stackpush(Stack*, int);
int stackpop(Stack*);
void stackdispose(Stack*);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment