Skip to content

Instantly share code, notes, and snippets.

@kgabis
Forked from mbelicki/stack.c
Created September 14, 2011 17:47
Show Gist options
  • Save kgabis/1217227 to your computer and use it in GitHub Desktop.
Save kgabis/1217227 to your computer and use it in GitHub Desktop.
Linked stack in C
#include "stack.h"
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <assert.h>
void stackpush(Stack ** stack, int value)
{
assert(stack != NULL);
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 removed_value;
}
void stackdispose(Stack * stack)
{
while(stack != NULL)
stackpop(&stack);
}
typedef struct node_t
{
int value;
struct node_t * lower;
} Node;
typedef struct node_t 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