堆栈的链式存储结构实现

#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; 

}

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值