学习过函数栈帧的朋友们都知道栈是一个能存放数据的地方今天我们就来开始栈的实践
如果您特别需要代码请自取:
void STInit(ST* pst)
{
assert(pst);
pst->a = NULL;
pst->capacity = 0;
pst->top = 0;
}
void STDestroy(ST* pst)
{
assert(pst);
free(pst->a);
pst->a = NULL;
pst->capacity = pst->top = 0;
}
void STPush(ST* pst, STDatetype x)
{
assert(pst);
if (pst->top == pst->capacity)
{
STDatetype newnode = pst->capacity = 0 ? 4 : pst->capacity * 2;
STDatetype* tmp = (STDatetype*)realloc(pst->a, sizeof(STDatetype) * newnode);
if (tmp == NULL)
{
perror("raelloc fail");
return -1;
}
pst->a = tmp;
pst->capacity = newnode;
}
pst->a[pst->top] = x;
pst->top++;
}
void STPop(ST* pst)
{
assert(pst);
assert(pst->top > 0);
pst->top--;
}
STDatetype STTop(ST* pst)
{
assert(pst);
assert(pst->top > 0);
return pst->a[pst->top-1];
}
bool STEmpty(ST* pst)
{
return pst->top == 0;
}
STDatetype STSize(ST* pst)
{
assert(pst);
return pst->top;
}
一、实现栈要求的功能
栈的初始化、栈的销毁、能存放数据(入栈)、能弹出数据(出栈)、获取栈顶元素、获取栈中的有效元素个数、对栈进行检查(判断栈是否为空)等要求需要实现。
二、栈的实现
1、栈的初始化
思路解析:
直接对指向空间置为NULL,并把栈顶和容量置为0。
代码实现:
void STInit(ST* pst)
{
assert(pst);
pst->a = NULL;
pst->capacity = pst->top = 0;
}
2、栈的销毁
思路解析:
利用free函数直接对指向的空间进行释放并把指针置为空,把栈顶和容量均置为0。
代码实现:
void STDestroy(ST* pst)
{
assert(pst);
free(pst->a);
pst->a = NULL;
pst->capacity = 0;
pst->top = 0;
}
3、入栈
思路解析:
1、初始化没有给空间所以我们一开始就要对空间进行扩容
2、然后把需要插入的数据利用栈顶直接插入
3、因为我们初始化时是把top置为0,所以我们在插入数据后要把top++方便后续的数据插入。
代码实现:
void STPush(ST* pst, STDatetype x)
{ assert(pst);
if(pst->top==pst->capacity)
{
STDatetype space = pst->capacity = 0 ? 4 : pst->capacity * 2;
STDatetype* newnode = (STDatetype*)realloc(pst->a, sizeof(STDatetype) * space);
if (newnode == NULL)
{
perror("realloc");
return -1;
}//扩容结束
pst->a = newnode;
pst->capacity = space;
}
pst->a[pst->top] = x;
pst->top++;
}
4、出栈
思路解析:
直接利用top--让最上面的元素出栈即可。
代码实现:
void STPop(ST* pst)
{
assert(pst);
assert(pst->top > 0);
pst->top--;
}
5、获取栈顶元素
思路解析:
pst的top是指向已存储的元素的下一个所以要获取栈顶元素只要top--就能通过数组a进行访问了。
代码实现:
STDatetype STTop(ST* pst)
{
assert(pst);
assert(pst->top > 0);
return pst->a[pst->top-1];
}
6、获取栈中有效元素个数
思路解析:
我们利用数组a和成员top来进行数组的访问即top的个数就是数组中的有效元素个数。
代码实现:
STDatetype STSize(ST* pst)
{
assert(pst);
return pst->top;
}
7、对栈进行检查
思路解析:
直接对pst->top进行判断即可。
代码实现:
bool STEmpty(ST* pst)
{
assert(pst);
if(pst->top==0)
{
return ture;
}
else
{
return false;
}
}