赞
踩
栈的概念:
栈的图示:
栈的判空:
栈的判空有二种实现方式,一种是top赋为0,一种是top赋为-1。区别:是top为0的时候,是先赋值再++,top为-1的时候相反。
下面是源码:
- void StackInit(Stack* ps)
- {
- assert(ps);
- ps->a = NULL;
- ps->capacity = ps->top = 0;
- }
-
- void StackPush(Stack* ps, STDateType x)
- {
- assert(ps);
-
- if (ps->top == ps->capacity)
- {
- int newcapacity = ps->capacity == 0 ? 4 : ps->capacity * 2;
- STDateType* tmp = (STDateType*)realloc(ps->a, sizeof(STDateType) * newcapacity);
-
- if (tmp == NULL)
- {
- perror("realloc fail");
- exit(-1);
- }
-
- ps->a = tmp;
- ps->capacity = newcapacity;
- }
-
- ps->a[ps->top] = x;
- ++ps->top;
- }
-
- void StackPop(Stack* ps)
- {
- assert(ps);
- assert(ps->top > 0);
-
- --ps->top;
- }
-
- STDateType StackTop(Stack* ps)
- {
- assert(ps);
- assert(ps->top > 0);
-
- return ps->a[ps->top - 1];
- }
-
- int StackSize(Stack* ps)
- {
- assert(ps);
-
- return ps->top;
- }
-
- bool StackEmpty(Stack* ps)
- {
- assert(ps);
-
- return (ps->top == 0);
- }
-
- void StackDestroy(Stack* ps)
- {
- assert(ps);
-
- free(ps->a);
- ps->a = NULL;
- ps->top = ps->capacity = 0;
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。