/* stack.c * * Example for CS 313 (compare to Pascal version stack.p!) * * Daniel Scharstein * * to compile, use gcc -W -Wall -o stack stack.c */ #include /* for printf */ #include /* for malloc, free */ struct elt { int val; struct elt *next; }; typedef struct elt *intlist; intlist mystack; /* global variable - generally considered bad style. * Don't use in your homework! */ void push(int n) /* push n on stack */ { intlist e = (intlist)malloc(sizeof(struct elt)); /* allocates new memory */ e->val = n; e->next = mystack; mystack = e; } int empty() /* return whether is stack empty */ { return (mystack == NULL); } int pop() /* pop a value off stack and return it */ { if (empty()) return 0; else { intlist e = mystack; int v = e->val; mystack = mystack->next; free(e); /* frees memory that was used to hold first elt */ return v; } } void printstack() /* print current contents of stack */ { intlist e; printf("Stack: "); for (e = mystack; e != NULL; e = e->next) printf("%d ", e->val); printf("\n"); } /* main program: */ int main() { int i; mystack = NULL; for (i=1; i<=5; i++) { printf("Push %d\n", i); push(i); } printf("Pop %d\n", pop()); printstack(); printf("Pop %d\n", pop()); printf("Push %d\n", 6); push(6); while (! empty()) printf("Pop %d\n", pop()); printf("top %d\n", mystack->val); return 0; }