#include<stdio.h>
#include<stdlib.h>
#include<string.h>
typedef struct StackNode{
int data;//数据域
struct StackNode* next;//指针域
}StackNode, *StackLink;//用于指向该类型结构体
typedef struct StackNodePre node;
struct StackNodePre{
StackLink top;// 栈顶指针
int amount;//计算栈内元素的数量
};
node* Push(node* S, int PushAmount)//栈顶结构体指针 压入值
{
if(S->amount==0){
//栈为空
StackNode* p = (StackNode*)malloc(sizeof(StackNode));
S->top = p;
p->next = NULL;
p->data = PushAmount;
++S->amount;
printf("\n成 功 压 入 !\n");
return S;
}else{
StackNode* p = (StackNode*)malloc(sizeof(StackNode));
p->next = S->top;
p->data = PushAmount;
S->top = p;
++S->amount;
printf("\n成 功 压 入 !\n");
return S;
}
}
node* Pop(node* S)
{
if(S->amount==0){
printf("\n栈 为 空!\n");
return S;
}else{
StackLink p;
p = S->top;//保存
printf("\np->data = %d\n", p->data);
S->top = S->top->next;//移动栈顶指针
free(p);
--S->amount;
printf("\n成 功 弹 出!\n");
return S;
}
}
int main()
{
int i = 0,PushAmount;
node* p = (node* )malloc(sizeof(node));
p->top = NULL;
p->amount = 0;
while(1)//压入操作
{
printf("请输入您要选择存储的数:\t");
scanf("%d", &PushAmount);
p = Push(p, PushAmount);
printf("\n\n请选择是否继续存储?如果停止,请输入 1 :\t");
scanf("%d",&i);
if(i==1){
break;
}
printf("\n\n");
}
printf("\n");
printf("请选择是否释放所存储的数?(选择:yes或no)\t");
char sum[4];
int Qr;
scanf("%s", sum);
if (strcmp(sum, "yes") == 0) {
for( ; ; ){
printf("\n请确认您是否选择此次释放:(1表示确认,其他表示退出)\t");
scanf("%d",&Qr);
if(Qr==1){
p = Pop(p);
}
else{
while(p->top){
StackNode* h = p->top;
p->top = p->top->next;
free(h);
}
free(p);
exit(0);
}
}
}
else if (strcmp(sum, "no") == 0) {
while(p->top){
StackNode* h = p->top;
p->top = p->top->next;
free(h);
}
free(p);
exit(1);
printf("\n");
}
else {
printf("ERROR!!!\n");
while(p->top){
StackNode* h = p->top;
p->top = p->top->next;
free(h);
}
free(p);
exit(1);
}
return 0;
}
堆栈的链式存储结构实现
猜你喜欢
转载自blog.csdn.net/qq_52001969/article/details/113261099
今日推荐
周排行