C语言 栈的初始化,入栈,出栈,判断栈是否为空,清空栈等函数
作者:互联网
#include <stdio.h>
#include <stdlib.h>
typedef struct Node
{
int data ;
struct Node * pNext;
}*PNODE ,NODE ;
typedef struct stack
{
PNODE pTop;
PNODE pBottom;
}*PSTACK ,STACK;
void init(PSTACK pS);
void push(PSTACK pS,int val);
void show(PSTACK pS);
bool is_empty(PSTACK pS);
bool pop(PSTACK pS,int * pVal);
void clear(PSTACK pS);
int main()
{
STACK S ;//定义了一个静态的栈,是程序员不能自己释放的
int val ;
init(&S);
push(&S,1);
push(&S,2);
push(&S,3);
push(&S,4);
show(&S);
if(pop(&S,&val))
{
printf("出栈成功,出栈的元素是:%d\n",val);
}
else printf("出栈失败!");
show(&S);
clear(&S);
show(&S);
}
void init(PSTACK pS)
{
pS->pTop = (PNODE)malloc(sizeof(NODE));
pS->pBottom =pS->pTop ;
pS->pTop->pNext = NULL ;
}
void push(PSTACK pS,int val)
{
PNODE pNew =(PNODE)malloc(sizeof(NODE));
pNew->data =val;
pNew->pNext =pS->pTop;
pS->pTop =pNew ;
}
void show(PSTACK pS)
{
PNODE p =pS->pTop ;
while(p!=pS->pBottom)
{
printf("%d ",p->data);
p=p->pNext ;
}
printf("\n");
}
bool is_empty(PSTACK pS)
{
if(pS->pTop==pS->pBottom)
return true ;
else return false ;
}
bool pop(PSTACK pS,int * pVal)
{
if(is_empty(pS))
{
return false ;
}
else
{
PNODE r = pS->pTop;
*pVal =r->data;
pS->pTop = r->pNext;
free(r);
r=NULL;
}
return true ;
}
void clear(PSTACK pS)
{
if(is_empty(pS))
{
return ;
}
else
{
PNODE p =pS->pTop;
PNODE q ;
while(q!=pS->pBottom)
{
q=p->pNext;
free(p);
p=q ;
}
}
pS->pTop=pS->pBottom;
}
标签:pS,出栈,入栈,int,void,PSTACK,C语言,PNODE,pTop 来源: https://www.cnblogs.com/cocobear9/p/12261891.html