思想:
1、栈模型:基本操作有Push(入栈)和Pop(出栈),元素符合先进后出,即最先入栈的元素最后出栈。
2、链式:主要以链表的形式构成一个栈。入栈即是采用头插法构造链表(符合先进后出),出栈只要遍历链表即可,并记录栈顶元素。最后将链表释放。
3、数组:首先我们可以直接使用数组(array)构造栈,利用top(初始化为-1),元素进栈则top+1,array[top]=元素x,出栈top-1,出栈时记录栈顶元素。但是这样就伴随这一个问题,就是我们要提前声明数组的大小,如果申请空间过大,造成资源浪费。可以试用结构体来解决。结构体包括Capacity(容量),TopofStack(栈顶记录),array(数组)。
链式栈代码:
#include
结果:
![7da662c27a8740c2c192c024f2e8788d.png](https://i-blog.csdnimg.cn/blog_migrate/5b6343a2d034c45da58ef1c38de414a4.png)
数组栈:
#include<stdio.h>
#include<stdlib.h>
#define Empty -1
#define MinStackSize 5
typedef struct StackRecord {
int Capacity;
int TopofStack;
int* array;
}*Stack;
int IsEmpty(Stack S);//判断栈是否为空
int IsFull(Stack S);//判断栈是否已满
Stack CreateStack(int ElementDigits);//给数组分配合适的空间
void DisposeStack(Stack S);//释放栈
int MakeEmpty(Stack S);//置空栈
void Push(Stack S);
int Top(Stack S);
void Pop(Stack S);//置空栈
//初始化Top
int MakeEmpty(Stack S) {
return S->TopofStack =Empty;
}
int IsEmpty(Stack S) {
return S->TopofStack==Empty;
}
int IsFull(Stack S) {
return S->TopofStack == S->Capacity;
}
//释放空间
void DisposeStack(Stack S) {
if(S!= NULL) {
free(S->array);
free(S);
}
}
//分配空间
Stack CreateStack(int ElementDigits) {
Stack S;
if (ElementDigits < MinStackSize) {//至少向栈中输入5个数
printf("StackSize is too small");
return 0;
}
S =(Stack)malloc(sizeof(struct StackRecord));
if (S == NULL) {
printf("out of space");
return 0;
}
S->array = (int*)malloc(sizeof(int) * ElementDigits);
if (S->array ==NULL) {
printf("out of space");
return 0;
}
S->Capacity = ElementDigits;
MakeEmpty(S);
return S;
}
//入栈
void Push(Stack S) {
int x;
if (IsFull(S)) {
printf("stack is full");
}
for (int i = 0; i < S->Capacity; i++) {
scanf_s("%d",&x);
S->array[++S->TopofStack] = x;
}
}
//返回栈顶元素
int Top(Stack S) {
if (!IsEmpty(S)) {
return S->array[S->TopofStack];
}
else {
printf("empty stackt");
return 0;
}
}
//出栈
void Pop(Stack S) {
int top;
while (!IsEmpty(S)) {
printf("%d出栈t", S->array[S->TopofStack--]);
top=Top(S);
printf("top is%dn",top);
}
}
int main() {
Stack S;
int num;
printf("输入入栈的个数:");
scanf_s("%d", &num);
S = CreateStack(num);
Push(S);
Pop(S);
DisposeStack(S);
return 0;
}
结果:
![a0ee68a42c8103bbd54f5f7728324afc.png](https://i-blog.csdnimg.cn/blog_migrate/fccc0504152962346aa1c77d5737bb17.png)