目录
栈的相关概念及结构
栈是限定仅在表尾进行插入和删除操作的线性表。允许插入和删除的一端称为栈顶,另一端称为栈底,不含任何元素的栈称为空栈。栈又称为后进先出的线性表。
栈的实现
定义一个栈
typedef int DataType;
typedef struct Stack
{
DataType* a; //柔性数组,存储栈元素
int top; //栈顶
int capacity; //容量
}ST;
栈相关接口函数
#define _CRT_SECURE_NO_WARNINGS
#include "Stack.h"
//初始化
void STInit(ST* pst)
{
assert(pst);
pst->a = NULL;
pst->top = -1;
pst->capacity = 0;
}
//销毁
void STDestony(ST* pst)
{
assert(pst);
assert(pst->a);
free(pst->a);
pst->a = NULL;
pst->top = -1;
pst->capacity = 0;
}
//入栈
void STPush(ST* pst, DataType x)
{
assert(pst);
if (pst->top + 1 == pst->capacity)
{
int newcapacity = pst->capacity == 0 ? 4 : pst->capacity * 2;
DataType* tmp = (DataType*)realloc(pst->a, newcapacity * sizeof(DataType));
if (tmp == NULL)
{
perror("realloc fail!");
return;
}
//将新申请的空间给数组和容量
pst->a = tmp;
pst->capacity = newcapacity;
}
pst->a[pst->top + 1] = x;
pst->top++;
}
//出栈
void STPop(ST* pst)
{
assert(pst);
assert(pst->top > -1);
//DataType* e;
//e = pst->a[pst->top];
pst->top--;
//return e;
}
//取栈顶元素
DataType STTop(ST* pst)
{
assert(pst);
assert(pst->top > -1);
return pst->a[pst->top];
}
//栈的大小
int STSize(ST* pst)
{
assert(pst);
return pst->top + 1;
}
//判空
bool STEmpty(ST* pst)
{
assert(pst);
return pst->top == -1;
}
两栈共享空间
用一个数组来存储两个栈。数组有两个端点,两个栈有两个栈底,让一个栈的栈底为数组的始端,即下标为0处,另一个栈为数组的末端,即下标为数组长度n-1处。
栈1为空时,就是top1等于-1时;当top2等于n时,即是栈2为空时。
若栈2是空栈,栈1的top1等于n-1时,就是栈1满了;若栈1为空栈时,top2等于0时,栈2满;
top1 + 1 = top2时,为栈满。
队列的相关概念及结构
队列是只允许在一端进行插入操作,而在另一端进行删除操作的线性表。
队列是一种先进先出的线性表。允许插入的一端称为队尾,允许删除的一端称为对头。
队列的实现
定义队列
typedef struct QueueNode
{
struct QueueNode* next;
DataType val;
}QNode;
typedef struct Queue
{
QNode* head;
QNode* tail;
int size;
}Queue;
队列相关接口函数
//初始化
void QueueInit(Queue* q)
{
assert(q);
q->head = NULL;
q->tail = NULL;
q->size = 0;
}
//销毁
void QueueDestory(Queue* q)
{
assert(q);
QNode* pcur = q->head;
while (pcur)
{
QNode* next = pcur->next;
free(pcur);
pcur = next;
}
q->head = NULL;
q->tail = NULL;
q->size = 0;
}
//对尾插入
void QueuePush(Queue* q, DataType x)
{
assert(q);
//申请节点
QNode* newnode = (QNode*)malloc(sizeof(QNode));
if (newnode == NULL)
{
perror("malloc fail");
return;
}
newnode->next = NULL;
newnode->val = x;
if (q->tail == NULL)
{
q->head = q->tail = newnode;
}
else
{
q->tail->next = newnode;
q->tail = newnode;
}
q->size++;
}
//对头删除
void QueuePop(Queue* q)
{
assert(q);
assert(q->size > 0);
if (q->head->next == NULL)
{
free(q->head);
q->head = q->tail = NULL;
}
else
{
QNode* next = q->head->next;
free(q->head);
q->head = next;
}
q->size--;
}
//取对头数据
DataType QueueFront(Queue* q)
{
assert(q);
assert(q->head);
return q->head->val;
}
//取队尾数据
DataType QueueBack(Queue* q)
{
assert(q);
assert(q->head);
return q->tail->val;
}
//队列大小
int QueueSize(Queue* q)
{
assert(q);
return q->size;
}