Skip to content

Instantly share code, notes, and snippets.

@kgabis
Created September 14, 2011 18:30
Show Gist options
  • Save kgabis/1217361 to your computer and use it in GitHub Desktop.
Save kgabis/1217361 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>
#include <assert.h>
void stackpush(Stack * stack, int value)
{
assert(stack != NULL);
if(stack->top == NULL)
{
stack->top = malloc(sizeof(Node));
stack->top->value = value;
stack->isempty = false;
}
else
{
Node * old = stack->top;
stack->top = malloc(sizeof(Node));
stack->top->next = old;
stack->top->value = value;
}
}
int stackpop(Stack * stack)
{
assert(stack != NULL);
int value = stack->top->value;
Node * oldtop = stack->top;
stack->top = stack->top->next;
free(oldtop);
if(stack->top == NULL)
stack->isempty = true;
return value;
}
void stackdispose(Stack * stack)
{
assert(stack != NULL);
while(! stack->isempty)
stackpop(stack);
}
typedef struct node_t
{
int value;
struct node_t * next;
} Node;
typedef struct stack_t
{
Node * top;
int isempty;
} 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