#include"stack.h"
#include<malloc.h>
#include<assert.h>
#include<stdio.h>
#include<string.h>
void stackInit(stack* ps)
{
assert(ps);
ps->array = (SDataType*)malloc(sizeof(SDataType)* 10);
if (NULL == ps->array)
{
assert(0);
return;
}
ps->capacity = 10;
ps->size = 0;
}
Checkcapacity(stack* ps)
{
assert(ps);
if (ps->size == ps->capacity)
{
//开辟新空间
SDataType* temp = (SDataType*)malloc(sizeof(SDataType)*ps->size * 2);
if (temp == NULL)
{
assert(0);
return;
}
//拷贝元素
memcpy(temp, ps->array, sizeof(SDataType)*ps->size);
//释放就空间
free(ps->array);
//使用新空间
ps->array = temp;
ps->capacity *= 2;
}
}
void stackPush(stack* ps, SDataType data)
{
assert(ps);
Checkcapacity(ps);
ps->array[ps->size++] = data;
}
void stackPop(stack* ps)
{
if (stackEmpty(ps))
return;
ps->size--;
}
SDataType stackTop(stack* ps)
{
assert(!stackEmpty(ps));
return ps->array[ps->size - 1];
}
int stackSize(stack* ps)
{
assert(ps);
return ps->size;
}
int stackEmpty(stack* ps)
{
assert(ps);
return ps->size == 0;
}
void stackDestroy(stack* ps)
{
assert(ps);
free(ps->array);
ps -> array = NULL;
ps->capacity = 0;
ps->size = 0;
}
栈的实现
最新推荐文章于 2022-12-21 10:56:03 发布