#include<stdio.h>
#include<malloc.h>
#include<stdlib.h>
typedef struct Node
{
int data;
struct Node *pNext;
}NODE,*PNODE;
typedef struct Stack
{
PNODE pTop;
PNODE pBottom;
}STACK,*PSTACK;
void init(PSTACK);
void push(PSTACK,int);
void traverse(PSTACK);
bool pop(PSTACK,int *);
void clear(PSTACK pS);
int main(void)
{
STACK S;//STACK 等价于 struct Stcak S
int val;
init(&S);//初始化
push(&S,1);
push(&S,2);
push(&S,3);
push(&S,4);
push(&S,5);
push(&S,6);
if(pop(&S,&val))
{
printf("success!");
printf("出栈的元素为:%d",val);
}
traverse(&S);//遍历输出
return 0;
}
void init(PSTACK pS)
{
pS->pTop=(PNODE)malloc(sizeof(NODE));
if(NULL==pS->pTop)
{
printf("error!");
exit(-1);
}
else
{
pS->pBottom=pS->pTop;
pS->pTop->pNext=NULL;//等价于pS->Bottom->pNext
}
}
void push(PSTACK Ps,int val)
{
PNODE pNew=(PNODE)malloc(sizeof(NODE));
pNew->data=val;
pNew->pNext=Ps->pTop;//不能写成Ps->pBottom
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;
}
bool empty(PSTACK pS)
{
if(pS->pTop==pS->pBottom)
return true;
else
return false;
}
//把pS所指向的栈出栈一次,并把出栈的元素存入pVal形参,如果出栈失败返回false;
bool pop(PSTACK pS,int *pVal)
{
if((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(empty(pS))
{
return;
}
PNODE p=pS->pTop;
PNODE q=p->pNext;
while(p!=pS->pBottom)
{
q=p->pNext;
free(p);
p=q;
}
pS->pTop=pS->pBottom;
}
堆栈
最新推荐文章于 2022-06-22 09:33:36 发布