一:栈的数学性质:
当n个不同的元素进栈时,元素越多,则出栈的顺序越多样化,这时我们可以用到卡特兰数公式,即:当n个不同元素进栈时,出栈元素不同排列的个数为
二:栈的操作特性:
先进先出
三:栈的基本操作代码:
#include<stdio.h>
#define MaxSize 20
typedef int ElemType;
typedef struct {
ElemType data[MaxSize];//定义一个数组,存放栈中元素
int top;//“栈顶指针”,在这里的应用实际就是数组的下标的一个
}SqStack;
//初始化
void InitStack(SqStack& S) {
S.top = -1;
}
//判空
bool StackEmpty(SqStack& S) {
if (S.top == -1) return true;
else return false;
}
//进栈
bool Push(SqStack& S, ElemType x) {
if (S.top == MaxSize - 1) return false;
S.data[++S.top] = x;//指针先加一,再入栈
printf("%d ", x);
return true;
}
//出栈
bool Pop(SqStack& S,ElemType x) {
if (S.top == -1) return false;
x = S.data[S.top--];//先出栈,指针再减一
return true;
}
//读栈顶元素
bool GetTop(SqStack S, ElemType x) {
if (S.top == -1) return false;
x = S.data[S.top]; return true;
printf("栈顶元素为:%d\n", x);
}
int main() {
SqStack S;
InitStack(S);
ElemType x;
printf("请输入一系列进栈元素,且以-1结束:");
scanf("%d", &x);
while (x != -1) {
Push(S, x);
scanf("%d", &x);
}
}
四:运行截图: