Skip to content

Instantly share code, notes, and snippets.

@lnsp
Last active August 29, 2015 14:17
Show Gist options
  • Save lnsp/25e7f1684171b40d0290 to your computer and use it in GitHub Desktop.
Save lnsp/25e7f1684171b40d0290 to your computer and use it in GitHub Desktop.
The best stack structure ever!
/*
A Stack structure implementation
(c) 2015 mooxmirror
*/
#include "stack.h"
Stack * Stack_create()
{
Stack * s = (Stack *) malloc(sizeof(Stack));
s->top = NULL;
return s;
}
void Stack_destroy(Stack * s)
{
Stack_item * current = s->top;
while (current != NULL) {
Stack_item * next = current->next;
free(current);
current = next;
}
free(s);
}
Stack_value Stack_peek(Stack * s)
{
Stack_item * top = s->top;
if (top != NULL)
return top->value;
return STACK_VALUE_NULL;
}
Stack_value Stack_pull(Stack * s)
{
Stack_item * top = s->top;
if (top != NULL)
{
Stack_value value = top->value;
Stack_item * tmp = top->next;
s->top = tmp;
free(top);
return value;
}
return STACK_VALUE_NULL;
}
void Stack_put(Stack * s, Stack_value value)
{
Stack_item * top = s->top;
Stack_item * next = malloc(sizeof(Stack_item));
next->value = value;
next->next = top;
s->top = next;
}
int Stack_empty(Stack * s)
{
return s->top == NULL;
}
/*
A stack structure implementation
(c) 2015 mooxmirror
*/
#ifndef STACK_H
#define STACK_H
#include <stdlib.h>
#include <stdio.h>
#define STACK_TYPE int
#define STACK_VALUE_NULL 0
typedef struct Stack Stack;
typedef struct Stack_item Stack_item;
typedef STACK_TYPE Stack_value;
struct Stack
{
Stack_item * top;
};
struct Stack_item
{
Stack_value value;
Stack_item * next;
};
Stack * Stack_create();
void Stack_destroy(Stack * s);
Stack_value Stack_peek(Stack * s);
Stack_value Stack_pull(Stack * s);
void Stack_put(Stack * s, Stack_value v);
int Stack_empty(Stack * s);
#endif
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment