#include<stdio.h>
#include<malloc.h>
#include<stdlib.h>
typedef struct Node
{
int date;//数据域
struct Node* PNext;
}NODE,*PNODE;
typedef struct Stack
{
PNODE PTop;//头部
PNODE PBottom;//尾部
}STACK,*PSTACK;
void init(PSTACK);//完成初始化
void push(PSTACK,int);//完成压栈
bool pop(PSTACK,int *pval);//实现出栈
void traverse_Stack(PSTACK PS);//实现遍历
void clear(PSTACK);//清空有效元素,但是结构仍然存在
int main()
{
int val;
STACK S;
init(&S);
push(&S,1);
push(&S,2);
push(&S,3);
push(&S,4);
traverse_Stack(&S);
clear(&S);
if(pop(&S,&val))
printf("出栈成功!出栈的元素是%d\n",val);
else
printf("出栈失败!\n");
traverse_Stack(&S);
return 0;
}
void init(PSTACK PS)
{
PS->PBottom=(PNODE)malloc(sizeof(NODE));
if(NULL==PS->PBottom)
{
printf("动态内存分配失败!\n");
exit(-1);
}
PS->PTop=PS->PBottom;
PS->PBottom->PNext=NULL;
return;
}
void push(PSTACK PS,int val)
{
PNODE PNew=(PNODE)malloc(sizeof(NODE));
if(NULL==PNew)
{
printf("动态内存分配失败!\n");
exit(-1);
}
PNew->date=val;
PNew->PNext=PS->PTop;
PS->PTop=PNew;
}
bool is_empty(PSTACK PS)
{
if(PS->PBottom==PS->PTop)
return true;
else
return false;
}
bool pop(PSTACK PS,int*pval)
{
if(is_empty(PS))
return false;
else
{
PNODE p=PS->PTop;
*pval=p->date;
PS->PTop=p->PNext;
free(p);
return true;
}
}
void traverse_Stack(PSTACK PS)
{
PNODE p=PS->PTop;
while(p->PNext!=NULL)
{
printf("%d\n",p->date);
p=p->PNext;
}
}
void clear(PSTACK PS)
{
PNODE p=PS->PTop;
PNODE q=p->PNext;
while(q!=NULL)
{
PS->PTop=q;
free(p);
p=q;
q=p->PNext;
}
}
通过指针实现栈
最新推荐文章于 2024-05-20 14:53:25 发布