Skip to content

Commit

Permalink
added stack ADT
Browse files Browse the repository at this point in the history
  • Loading branch information
edma2 committed Jan 19, 2011
1 parent 297c0fb commit 9f0873e
Show file tree
Hide file tree
Showing 2 changed files with 66 additions and 0 deletions.
52 changes: 52 additions & 0 deletions stack.c
@@ -0,0 +1,52 @@
#include "stack.h"

/*
* [item]-->[item]-->[item]-->[item]-->NULL
* ^ top ^bottom
*/

Stack *stack_new(void) {
return NULL;
}

int stack_isempty(Stack *s) {
return (s == NULL);
}

void *stack_top(Stack *s) {
if (stack_isempty(s))
return NULL;
return s->item;
}

void stack_free(Stack *s) {
while (!stack_isempty(s))
stack_pop(&s);
}

/* Push new item onto stack */
void stack_push(Stack **s, void *item) {
Stack *top;

top = malloc(sizeof(Stack));
if (top == NULL)
return;
top->item = item;
top->next = *s;
*s = top;
}

/* Pop stack and return item */
void *stack_pop(Stack **s) {
Stack *next;
void *item;

if (*s == NULL)
return NULL;
next = (*s)->next;
item = (*s)->item;
free(*s);
*s = next;

return item;
}
14 changes: 14 additions & 0 deletions stack.h
@@ -0,0 +1,14 @@
#include <stdlib.h>

struct Stack {
struct Stack *next;
void *item;
};
typedef struct Stack Stack;

Stack *stack_new(void);
int stack_isempty(Stack *s);
void *stack_top(Stack *s);
void stack_push(Stack **s, void *item);
void *stack_pop(Stack **s);
void stack_free(Stack *s);

0 comments on commit 9f0873e

Please sign in to comment.