#include<stdio.h>
#include<stdlib.h>
#include<stdbool.h>
struct Node{
int data;
struct Node* next;
};
struct Stack{
struct Node* pTop;
struct Node* pBottom;
};
void init(struct Stack*);
void push(struct Stack*,int);
bool pop(struct Stack*,int*);
void traverse(struct Stack*);
void clean(struct Stack*);
int main(void)
{
int val;
struct Stack S;
init(&S);
push(&S,1);
push(&S,2);
push(&S,3);
push(&S,4);
push(&S,5);
traverse(&S);
if(pop(&S,&val))
{
printf("出栈的元素是%d\n",val);
}
else
{
printf("该栈为空,出栈失败!\n");
}
traverse(&S);
clean(&S);
traverse(&S);
return 0;
}
void init(struct Stack* pS)
{
struct Node *s=NULL;
s=(struct Node*)malloc(sizeof(struct Node));
if(NULL==s)
{
printf("动态内存申请失败!\n");
exit(-1);
}
else
{
pS->pTop=s;
pS->pBottom=s;
s->next=NULL;
}
return;
}
void push(struct Stack* pS,int val)
{
struct Node *p=(struct Node*)malloc(sizeof(struct Node));
if(NULL==p)
{
printf("动态内存申请失败!\n");
exit(-1);
}
p->data=val;
p->next=pS->pTop;
pS->pTop=p;
return;
}
bool pop(struct Stack* pS,int* pVal)
{
struct Node *p=NULL;
if(pS->pBottom==pS->pTop)
{
return false;
}
else
{
p=pS->pTop;
*pVal=p->data;
pS->pTop=p->next;
free(p);
return true;
}
}
void traverse(struct Stack* pS)
{
struct Node *p=pS->pTop;
while(p!=pS->pBottom)
{
printf("%d ",p->data);
p=p->next;
}
printf("\n");
return;
}
void clean(struct Stack* pS)
{
struct Node *p=pS->pTop,*q=NULL;
while(p!=pS->pBottom)
{
q=p->next;
free(p);
p=q;
}
pS->pTop=pS->pBottom;
return;
}
动态栈程序演示
最新推荐文章于 2024-07-24 19:27:25 发布