Permalink
Browse files

added stack ADT

  • Loading branch information...
1 parent 297c0fb commit 9f0873ed9f33d09fd8adcf5b3982a9bfc625ef7c @edma2 committed Jan 19, 2011
Showing with 66 additions and 0 deletions.
  1. +52 −0 stack.c
  2. +14 −0 stack.h
View
52 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;
+}
View
14 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.