1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
| #include <stdio.h> #include <stdlib.h> typedef struct Node { int value; struct Node *next; }Node; typedef struct { Node *top; int count; } Stack; bool init(Stack *s); bool push(Stack *s, int e); bool pop(Stack *s, int *e); int main() { int i, e; Stack s; init(&s); for (i = 0; i < 5; i++) { push(&s, i); pop(&s, &e); printf("%d\n", e); } return 0; } bool init(Stack *s) { s->top = NULL; s->count = 0; return true; } bool push(Stack *s, int e) { Node *newNode = (Node*)malloc(sizeof(Node)); if (NULL == newNode) { return false; } newNode->next = s->top; newNode->value = e; s->top = newNode; s->count ++; return true; } bool pop(Stack *s, int *e) { Node *temp = NULL; if (0 == s->count) { return false; } temp = s->top; *e = temp->value; s->top = temp->next; free(temp); s->count --; return true; }
|