#include #include #include "stack.h" /* Stack implementation is a linked list with a header */ struct node { elem data; ptr_to_node next; }; int is_empty(stack s) { return s->next == NULL; } stack create_stack() { stack s; s = malloc(sizeof(struct node)); if(s == NULL) printf("error"); make_empty(s); return s; } void make_empty(stack s) { if(s == NULL) printf("must create a stack first"); else while(!is_empty(s)) pop(s); } void push(elem x, stack s) { ptr_to_node tmp; tmp = malloc(sizeof(struct node)); if(tmp == NULL) printf("out of space"); else { tmp->data = x; tmp->next = s->next; s->next = tmp; } } void pop(stack s) { if(!is_empty(s)) { ptr_to_node tmp = s->next; s->next = s->next->next; free(tmp); } else printf("Empty stack"); } elem top(stack s) { // if(is_empty(s)) // printf("empty stack"); // else // return s->next->data; // // return -1; // /* tune version */ if(!is_empty(s)) return s->next->data; printf("empty stack"); return 0; } void print_stack(stack s) { printf("--------\n"); while(!is_empty(s)) { printf(" %d\n", s->next->data); s = s->next; } printf("--------\n"); } void test() { stack s; s = create_stack(); push(1, s); push(2, s); print_stack(s); push(3, s); push(4, s); push(5, s); print_stack(s); printf("%d\n",top(s)); pop(s); print_stack(s); pop(s); pop(s); pop(s); pop(s); pop(s); pop(s); print_stack(s); } int main() { test(); return 0; }