数据结构 --- 栈
1.栈的初始化
2.入栈
3.出栈
4.取出栈顶元素
5.获取栈中有效元素个数
6.栈的销毁
栈:⼀种特殊的线性表,其只允许在固定的⼀端进⾏插⼊和删除元素操作。进⾏数据插⼊和删除操作 的⼀端称为栈顶,另⼀端称为栈底。栈中的数据元素遵守后进先出LIFO(LastInFirstOut)的原则。
压栈:栈的插⼊操作叫做进栈/压栈/⼊栈,⼊数据在栈顶。
出栈:栈的删除操作叫做出栈。出数据也在栈顶
1.栈的初始化
#include<stdio.h>
#include<stdlib.h>
#include<assert.h>
#include<stdbool.h>//定义
typedef int STDataType;
struct Stack
{STDataType* arr;int capacity; int top; //记录栈顶元素
};
typedef struct Stack ST;//栈的初始化
void STInit(ST* ps)
{ps->arr = NULL;ps->capacity = 0;ps->top = 0;
}
2.入栈
#include<stdio.h>
#include<stdlib.h>
#include<assert.h>
#include<stdbool.h>//定义
typedef int STDataType;
struct Stack
{STDataType* arr;int capacity; int top; //记录栈顶元素
};
typedef struct Stack ST;//入栈
void STPush(ST* ps, STDataType x)
{assert(ps);if (ps->top == ps->capacity)//判断内存是否够 --- 如果栈顶等于栈容量大小,那么就需要扩容{int newcapacity = ps->capacity == 0 ? 4 : 2 * ps->capacity;STDataType* tmp = (STDataType*)realloc(ps->arr, newcapacity *sizeof(STDataType));if (tmp == NULL)//如果申请失败,则perror{perror("realloc fail");exit(1);}ps->capacity = newcapacity;ps->arr = tmp;}ps->arr[ps->top++] = x;//入栈
}
3.出栈
#include<stdio.h>
#include<stdlib.h>
#include<assert.h>
#include<stdbool.h>//定义
typedef int STDataType;
struct Stack
{STDataType* arr;int capacity; int top; //记录栈顶元素
};
typedef struct Stack ST;//判断栈是否为空
bool STEmpty(ST* ps)
{assert(ps);return ps->top == 0;//如果为0,则返回true,不为0返回false
}//出栈
void STPop(ST* ps)
{assert(!STEmpty(ps));//记得要取反 --- 栈不为空才可以出栈,否则就是非法访问--ps->top;//对栈顶--即可
}
4.取出栈顶元素
#include<stdio.h>
#include<stdlib.h>
#include<assert.h>
#include<stdbool.h>//定义
typedef int STDataType;
struct Stack
{STDataType* arr;int capacity; int top; //记录栈顶元素
};
typedef struct Stack ST;//判断栈是否为空
bool STEmpty(ST* ps)
{assert(ps);return ps->top == 0;//如果为0,则返回true,不为0返回false
}//取出栈顶元素
STDataType STTop(ST* ps)
{assert(!STEmpty(ps));//栈不为空才可以取栈顶 --- 否则就是非法访问
//方法一// STDataType tmp = ps->arr[ps->top - 1];// STPop(ps);// return tmp;
//方法二return ps->arr[ps->top - 1];
}
5.获取栈中有效元素个数
#include<stdio.h>
#include<stdlib.h>
#include<assert.h>
#include<stdbool.h>//定义
typedef int STDataType;
struct Stack
{STDataType* arr;int capacity; int top; //记录栈顶元素
};
typedef struct Stack ST;//获取栈中有效元素个数
int STSize(ST* ps)
{assert(ps);return ps->top;//我们在出栈和入栈都有记录top,所以直接返回top就是栈的有效元素个数
}
6.栈的销毁
//栈的销毁
void STDestroy(ST* ps)
{if (ps->arr)//如果ps->arr不为空,那么进入if,释放ps{free(ps->arr);}ps->arr = NULL;//置为空,避免成为野指针ps->capacity = 0;ps->top = 0;
}