//栈调用示例int main(void)
{
STACK stack; //定义一个栈变量,STACK等价于struct Stack
int val; //用来保存出栈的内容
initStack(&stack); //调用栈的初始化函数
pushStack(&stack, 10); //调用入栈的函数
pushStack(&stack, 20);
pushStack(&stack, 30);
pushStack(&stack, 50);
traverseStack(&stack); //调用遍历栈的函数
//调用出栈的函数
if(popStack(&stack, &val))
printf("出栈成功,出栈的元素值为:%d\n", val);
else
printf(" 出栈失败!");
//调用清空栈的函数
clearStack(&stack);
traverseStack(&stack); //调用遍历栈的函数
system("pause");
return 0;
}
//操作函数的实现
void initStack(PSTACK pStack)
{
//创建一个空结点,让pTop指向它
pStack->pTop = (PN ODE)malloc(sizeof(NODE));
if(NULL != pStack->pTop)
{
//将pBottom也指向空节点
pStack->pBottom = pStack->pTop;
//清空空结点的指针域
pStack->pTop->pNext = NULL;
}
else //如果内存分配失败
{
printf("内存分配失败!程序退出!\n");
exit(-1);
}
return;
}
void pushStack(PSTACK pStack, int val)
{
//动态创建一个新结点
PNODE pNew = (PNODE)malloc(sizeof(NODE));
//设置新结点的数据域的值
pNew->data = val;
//将新结点的指针域指向之前建的空节点
pNew->pNext = pStack->pTop; //pStack->pTop不能换成pStack->pBottom
//pTop指向新的结点
pStack->pTop = pNew;
return;
}
bool popStack(PSTACK pStack, int * pVal)
{
if(isEmpty(pStack))
{
return false;
}
else
{
//先保存栈顶元素的地址,然后将pTop指向下一元素,最后释放之前栈顶元素的内存
PNODE rNode = pStack->pTop;
*pVal = rNode->data;
pStack->pTop = rNode->pNext;
free(rNode);
rNode = NULL;
return true;
}
}
|