前言
该文章写了栈和队列的定义及其结构;栈和队列的基本操作包括代码的实现
一· 栈(stack)
1.1 栈的定义及其结构
1.1.1 栈的定义
一种特殊的线性表,其只允许在固定的一端进行插入和删除元素操作(后进先出)也就是头插头删!!!
1.1.2 栈的结构
typedef int STDatatype;
typedef struct Stack
{
STDatatype* a;
int top;
int capacity;
}ST;
- 进行数据插入和删除操作的一端称为栈顶,另一端称为栈底。
- 压栈:栈的插入操作叫做进栈/压栈/入栈,入数据在栈顶。
- 出栈:栈的删除操作叫做出栈。出数据也在栈顶。
从两个示意图中我们可以更详细的了解栈的后进先出特性
1.2 栈的基本操作及其代码的实现
1.2.1 栈的基本操作
- 入栈 解释: 将元素放到栈顶
- 出栈 解释: 删除栈顶元素
- 获取栈顶元素
- 栈中的有效个数
- 检测栈是否为空
1.2.2 代码的实现
- 入栈
//入栈 void Stackpush(ST* ps, STDatatype x) { assert(ps); if (ps->top == ps->capacity) { int newcapacity = ps->capacity == 0 ? 4 : ps->capacity * 2; STDatatype* tmp = (STDatatype*)realloc(ps->a, sizeof(STDatatype) * newcapacity); if (tmp == NULL) { perror("realloc"); return; } ps->a = tmp; ps->capacity = newcapacity; } ps->a[ps->top] = x; ps->top++; }
- 出栈
//出栈 void StackPop(ST* ps) { assert(ps); assert(ps->top > 0); ps->top--; }
- 获取栈顶元素
//获取栈顶元素 STDatatype StackTop(ST* ps) { assert(ps); assert(ps->top > 0); return ps->a[ps->top - 1]; }
- 栈中的有效个数
//栈中有效元素个数 int Stacksize(ST* ps) { assert(ps); return ps->top; }
二· 队列(Queue)
2.1队列的定义及其结构
只允许在一端进行插入数据操作,在另一端进行删除数据操作的特殊线性表,队列具有先进先出
FIFO(First In First Out) 入队列:进行插入操作的一端称为队尾 出队列:进行删除操作的一端称为队头
我们可以将队列的入地出队想象成我们平时食堂排队,先到先排先打饭(打完饭走了就是出队)
2.2队列的基本操作及其代码的实现
2.2.1基本操作
1. 队尾入
2. 队头删
3. 获取队头元素
4. 获取队尾元素
5. 获取队列中有效元素个数
6. 检测队列是否为空
2.2.2代码的实现
- 队尾入
//队尾入 void QueuePush(Queue* ps,QTadatype x) { assert(ps); QNode* newnode = (QNode*)malloc(sizeof(QNode)); if (newnode == NULL) { perror("malloc"); return; } //将开辟好的空间节点初始化 newnode->a = x; newnode->next = NULL; //插入数据 if (ps->phead == NULL) { ps->phead = ps->ptail = newnode; } else { ps->ptail->next = newnode; //ps->ptail类型是Qnode* //ps->ptail->next他的类型是QueueNode* //newnode类型是Qnode* ps->ptail = newnode;//尾指针 } ps->size++; }
- 对头删
//队头删 void QueuePop(Queue* ps) { assert(ps); assert(ps->phead); QNode* tmp = ps->phead; ps->phead = ps->phead->next; //Node* //只有一个节点的情况 if (ps->phead == NULL) { ps->ptail = NULL; } free(tmp); tmp = NULL; ps->size--; }
- 获取对头元素
//获取队头元素 QTadatype QueueFront(Queue* ps) { assert(ps); assert(ps->phead); return ps->phead->a; }
- 获取队尾元素
//获取队尾元素 QTadatype QueueBack(Queue* ps) { assert(ps); assert(ps->ptail); return ps->ptail->a; }
- 获取队列中有效元素个数
//获取队列中有效元素个数 int QueueSize(Queue* ps) { assert(ps); return ps->size; }
- 检测队列是否为空
//检测队列是否为空 bool QueueEmpty(Queue* ps) { assert(ps); return ps->phead == NULL; }