栈的初始化
void StackInit(StackNode* tail)
{
if (tail == NULL)
{
return;
}
tail->data = (STDataType*)malloc(sizeof(STDataType) * 4);
if (tail->data == NULL)
{
cout << "扩容失败" << endl;
return;
}
tail->capacity = 4;
tail->top = 0;
}
栈的销毁
void StackDestroy(StackNode* tail)
{
if (tail == NULL)
{
return;
}
free(tail->data);
tail->data = NULL;
tail->top = tail->capacity = 0;
}
入栈
void StackPush(StackNode* tail, STDataType x)
{
tail->data[tail->top] = x;
tail->top++;
if (tail == NULL)
{
return;
}
if (tail->top == tail->capacity)
{
STDataType* temp = (STDataType*)realloc(tail->data, (tail->capacity) *sizeof(STDataType)*2);
if (temp == NULL)
{
cout << "扩容失败" << endl;
}
else
{
tail->data = temp;
tail->capacity = (tail->capacity) * 2;
}
}
}
出栈
void StackPop(StackNode* tail)
{
if (tail == NULL)
{
return;
}
if (tail->top > 0)
{
tail->top --;
}
else
{
cout << "已经到栈顶了" << endl;
}
}
获得栈顶元素
STDataType StackTop(StackNode* tail)
{
if (tail == NULL)
{
return 0;
}
if (tail->top > 0)
{
return tail->data[tail->top - 1];
}
return 0;
}
获得栈的大小
int StackSize(StackNode* tail)
{
if (tail == NULL)
{
return 0;
}
return tail->top;
}
判断栈是否为空
bool StackEmpty(StackNode* tail)
{
if (tail == NULL)
{
return 0;
}
return tail->top == 0;
}
测试
void test()
{
StackNode st;
StackInit(&st);
StackPush(&st,1);
StackPush(&st, 2);
StackPush(&st, 3);
StackPush(&st, 4);
StackPush(&st, 5);
StackPush(&st, 6);
while (!StackEmpty(&st))
{
cout << StackTop(&st)<<" ";
StackPop(&st);
}
StackDestroy(&st);
}