题目:编写程序,从键盘输入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;
}