一、栈
栈:⼀种特殊的线性表,其只允许在固定的⼀端进⾏插⼊和删除元素操作。进⾏数据插⼊和删除操作的⼀端称为栈顶,另⼀端称为栈底。栈中的数据元素遵守后进先出LIF(Last In First Out)的原则
压栈:栈的插⼊操作叫做进栈/压栈/⼊栈,⼊数据在栈顶
出栈:栈的删除操作叫做出栈。出数据也在栈顶
栈的实现可以采取链表和数组两种形式,但是栈遵循后进先出(先进后出)的原则,要想节约空间、提高效率,应当采用数组作为栈的底层实现方式,因为数组在尾上插⼊数据的代价⽐较⼩
typedef int STDataType;
typedef struct Stack
{
STDataType* arr;
int top; //指向栈顶的位置
int capacity; //容量
}ST;
//栈的初始化
void STInit(ST* ps)
{
ps->arr = NULL;
ps->top = ps->capacity = 0;
}
//栈的销毁
void STDestroy(ST* ps) {
if (ps->arr) {
free(ps->arr);
}
ps->arr = NULL;
ps->capacity = ps->top = 0;
}
//将元素放在栈中
void StackPush(ST* ps, STDataType x) {
assert(ps);
if (ps->capacity == ps->top) {
int newCapacity = ps->capacity == 0 ? 4 : 2 * ps->capacity;
STDataType* tmp = (STDataType*)realloc(ps->arr, newCapacity * sizeof(STDataType));
if (tmp == NULL)
{
perror("realloc fail!");
exit(1);
}
ps->arr = tmp;
ps->capacity = newCapacity;
}
ps->arr[ps->top++] = x;
}
//判空
bool StackEmpty(ST* ps)
{
assert(ps);
return ps->top == 0;
}
//出栈----栈顶
void StackPop(ST* ps) {
assert(!StackEmpty(ps));
--ps->top;
}
//取栈顶数据
STDataType StackTop(ST* ps)
{
assert(!StackEmpty(ps));
return ps->arr[ps->top - 1];
}
//获取栈中有效元素个数
int STSize(ST* ps)
{
assert(ps);
return ps->top;
}
二、队列
概念:只允许在⼀端进⾏插⼊数据操作,在另⼀端进⾏删除数据操作的特殊线性表,队列具有先进先出FIFO(First In First Out)
⼊队列:进⾏插⼊操作的⼀端称为队尾
出队列:进⾏删除操作的⼀端称为队头
队列的实现方式和栈其实是很相似的,都是可以采取数组和链表作为底层实现形式,但这两个的时间复杂度都不太好,因此可以想到用一个结构体来直接包含队列的头和尾
//定义结点的结构
typedef int QDataTpe;
typedef struct QueueNode
{
QDataTpe data;
struct QueueNode* next;
}QueueNode;
//定义队列的结构
typedef struct Queue {
QueueNode* phead;//队头
QueueNode* ptail;//队尾
int size;//记录有效数据个数
}Queue;
//初始化队列
void QueueInit(Queue* pq) {
assert(pq);
pq->phead = pq->ptail = NULL;
pq->size = 0;
}
//销毁队列
void QueueDestroy(Queue* pq) {
assert(pq);
QueueNode* pcur = pq->phead;
while (pcur)
{
QueueNode* next = pcur->next;
free(pcur);
pcur = next;
}
pq->phead = pq->ptail = NULL;
}
//入队---队尾
void QueuePush(Queue* pq, QDataTpe x) {
QueueNode* newnode = (QueueNode*)malloc(sizeof(QueueNode));
if (newnode == NULL)
{
perror("malloc fail!");
exit(1);
}
newnode->data = x;
newnode->next = NULL;
//队列为空,newnode是队头也是队尾
if (pq->phead == NULL)
{
pq->phead = pq->ptail = newnode;
}
else {
//队列非空,直接插入到队尾
pq->ptail->next = newnode;
pq->ptail = pq->ptail->next;
}
pq->size++;
}
//判空
bool QueueEmpty(Queue* pq)
{
assert(pq);
return pq->phead == NULL;
}
//出队---队头
void QueuePop(Queue* pq) {
assert(!QueueEmpty(pq));
//只有一个结点的情况
if (pq->phead == pq->ptail)
{
free(pq->phead);
pq->phead = pq->ptail = NULL;
}
else {
QueueNode* next = pq->phead->next;
free(pq->phead);
pq->phead = next;
}
pq->size--;
}
//取队头数据
QDataTpe QueueFront(Queue* pq)
{
assert(!QueueEmpty(pq));
return pq->phead->data;
}
//取队尾数据
QDataTpe QueueBack(Queue* pq)
{
assert(!QueueEmpty(pq));
return pq->ptail->data;
}
//队列有效元素个数
int QueueSize(Queue* pq)
{
//int size = 0;
//QueueNode* pcur = pq->phead;
//while (pcur)
//{
// ++size;
// pcur = pcur->next;
//}
//return size;
return pq->size;
}