贴一些简单的栈的操作
- #include <stdio.h>
- #include <stdlib.h>
- #include <assert.h>
- #define bool int
- #define true 1
- #define false 0
- #define MAXVAL 100/*the max depth of stack*/
- #define Type float
- struct stack {
- int sp;/*the next free pos*/
- Type val[MAXVAL];
- };
- struct stack *init_stack()
- {
- struct stack *s = (struct stack*)malloc(sizeof(struct stack));
- if (s != NULL)
- s->sp = 0;
- return s;
- }
- bool push(struct stack *s, Type data)
- {
- assert(s != NULL);
- if (s->sp < MAXVAL) {
- s->val[s->sp++] = data;
- return true;
- } else {
- printf("error: stack full, can't push %g/n", data);
- return false;
- }
- }
- Type pop(struct stack *s)
- {
- assert(s != NULL);
- if (s->sp > 0)
- return s->val[--s->sp];
- else {
- printf("error: stack empty!/n");
- return 0.0;
- }
- }
- Type top(struct stack *s)
- {
- assert(s != NULL);
- if (s->sp > 0)
- return s->val[s->sp - 1];
- else {
- printf("error: stack empty!/n");
- return 0.0;
- }
- }
- void clear_stack(struct stack *s)
- {
- assert(s != NULL);
- s->sp = 0;
- }
- bool stack_empty(struct stack *s)
- {
- assert(s != NULL);
- if (s->sp > 0)
- return false;
- else
- return true;
- }
- int main()
- {
- struct stack *s = NULL;
- s = init_stack();
- push(s, 5.2);
- push(s, 4.8);
- push(s, 15);
- printf("%g ", pop(s));
- printf("%g ", pop(s));
- printf("%g ", top(s));
- printf("%g ", pop(s));
- printf("%g ", pop(s));
- free(s);
- return 0;
- }