#include<stdio.h>
#include<malloc.h>
#include<stdlib.h>
#include<stdbool.h>
typedef struct Node
{
int data;
struct Node * pNext;
}NODE,* PNODE;
typedef struct Stack
{
PNODE pTop;
PNODE pBottom;
}STACK,* PSTACK;
void initStack(PSTACK);
void pushStack(PSTACK,int);
void traverse(PSTACK);
bool pop(PSTACK,int *);
bool stack_isEmpty(PSTACK);
void clearNode(PSTACK pS);
int main(void)
{
STACK S;
int val;
initStack(&S);
pushStack(&S,1);
pushStack(&S,12);
pushStack(&S,21);
pushStack(&S,152);
pushStack(&S,-15);
pushStack(&S,89);
traverse(&S);
if(pop(&S,&val))
{
printf("操作成功,弹栈的值是:-----%d------\n",val);
}
else
{
printf("弹栈失败!!!\n");
}
traverse(&S);
clearNode(&S);//清除节点
if(pop(&S,&val))
{
printf("操作成功,弹栈的值是:%d\n",val);
}
else
{
printf("弹栈失败!!!\n");
}
return 0;
}
void initStack(PSTACK pS)
{
pS->pTop = (PNODE)malloc(sizeof(NODE));
if(pS->pTop == NULL)
{
printf("动态内存分配失败!!!\n");
exit(-1);
}
else
{
pS->pBottom = pS->pTop;
pS->pTop->pNext = NULL;
}
}
void pushStack(PSTACK pS,int val)
{
PNODE pNew = (PNODE)malloc(sizeof(NODE));
pNew->data = val;
pNew->pNext = pS->pTop;
pS->pTop = pNew;
return;
}
void traverse(PSTACK pS)
{
PNODE p = pS->pTop;
while(p != pS->pBottom)
{
printf("%d ",p->data);
p = p->pNext;
}
printf("\n");
return;
}
//把pS所指向的栈出栈一次,并把出栈的元素存入pVal所指向的变量中,如果出栈失败,返回false,成功返回true
bool pop(PSTACK pS,int *pVal)
{
if(stack_isEmpty(pS))
{
return false;
}
else
{
PNODE pos = pS->pTop;
*pVal = pS->pTop->data;
pS->pTop = pS->pTop->pNext;
free(pos);
pos = NULL;
return true;
}
}
bool stack_isEmpty(PSTACK pS)
{
if(pS->pTop == pS->pBottom)
{
return true;
}
else
{
return false;
}
}
//清空节点
void clearNode(PSTACK pS)
{
if(stack_isEmpty(pS))
{
return;
}
else
{
PNODE p = pS->pTop;
PNODE q = NULL;
while(p != pS->pBottom)
{
q = p->pNext;
free(p);
p = q;
}
pS->pTop = pS->pBottom;
}
}
郝斌数据结构 33 栈程序演示
最新推荐文章于 2020-08-04 10:58:22 发布