编写程序,从键盘输入10个数据压入栈中,然后从栈中依次弹出这些数据并输出。

题目:编写程序,从键盘输入10个数据压入栈中,然后从栈中依次弹出这些数据并输出。

重点:栈的特性:先进后出

1.基于数组的顺序栈结构声明:

struct Stack {
    int * Data;   // 栈空间
    int Top;      // 栈顶,为-1时表示空栈
    int MaxSize; //栈的最大容量
};

2.堆栈的创建:

struct Stack*Creat(int MaxSize){
	struct Stack*S;
	S=malloc(sizeof(struct Stack));
	S->Data=malloc(sizeof(int)*MaxSize);
	S->Top=-1;
	S->MaxSize=MaxSize;
	return S;
}

3.数据进栈:

void Push(struct Stack*S,int x){
if(S->Top==S->MaxSize){
printf("Stack is full");//若栈顶为栈的最大容量,则栈满
return;
}
S->Data[++S->Top]=x;
}

4,数据出栈:

int Pop(struct Stack*S){
	if(S->Top==-1){
		printf("Stack is empty");//如果没有元素,则栈为空
		return ;
	}
	return S->Data[S->Top--];//若有元素,出栈后栈顶元素发生改变。 
} 

5.实现源程序:

#include<stdio.h>
#include<stdlib.h> 
	struct Stack {
    int * Data;   // 栈空间
    int Top;      // 栈顶,为-1时表示空栈
    int MaxSize; //栈的最大容量
};
struct Stack*Creat(int MaxSize){
	struct Stack*S;
	S=malloc(sizeof(struct Stack));
	S->Data=malloc(sizeof(int)*MaxSize);
	S->Top=-1;
	S->MaxSize=MaxSize;
	return S;
}
void Push(struct Stack*S,int x){
	if(S->Top==S->MaxSize){
		printf("Stack is full");
		return;
	}
	S->Data[++S->Top]=x; 
}
int Pop(struct Stack*S){
	if(S->Top==-1){
		printf("Stack is empty");
		return ;
	}
	return S->Data[S->Top--]; 
} 
int main(){
	struct Stack*S;
	S=Creat(100);
	int i,n;
	printf("请输入十个整数:\n");
	for(i=0;i<10;i++){
		scanf("%d",&n);
		Push(S,n);
	}
    printf("输出整数为:\n");
	for(i=0;i<10;i++){
		printf("%d ",Pop(S));
	}
	return 0;
} 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值