前言
栈和队列也属于线性表,但是它们存取顺序有一定的顺序,本篇对其做重点讲解
一、栈:
1.栈的基本概念:
栈:一种特殊的线性表,其只允许在固定的一端进行插入和删除元素操作。进行数据插入和删除操作的一端称为栈顶,另一端称为栈底。栈中的数据元素遵守后进先出LIFO(Last In First Out)的原则。
存储数据:
- 压栈:栈的插入操作叫做进栈/压栈/入栈,入数据在栈顶。
- 出栈:栈的删除操作叫做出栈。出数据也在栈顶。
2.如何实现栈?
栈的实现一般可以使用数组或者链表实现,相对而言数组的结构实现更优一些。因为数组在尾上插入和删除数据的代价比较小。
3.栈代码演示:
void StackInit(Stack* ps)//栈的初始化
{
assert(ps);
ps->arr = NULL;
ps->top = 0;
ps->capacity = 0;
}
void StackDestroy(Stack* ps)//栈销毁
{
assert(ps);
free(ps->arr);
ps->arr = NULL;
ps->capacity = 0;
ps->top = 0;
}
void StackPush(Stack* ps, StackDataType x)//压栈
{
assert(ps);
if (ps->top == ps->capacity)
{
int newcapacity = ps->capacity == 0 ? 4 : ps->capacity * 2;
StackDataType* tmp = (StackDataType*)realloc(ps->arr, sizeof(StackDataType) * newcapacity);
if (tmp == NULL)
{
perror("realloc");
exit(-1);
}
ps->arr = tmp;
ps->capacity = newcapacity;
}
ps->arr[ps->top] = x;
ps->top++;
}
void StackPop(Stack* ps)//出栈
{
assert(ps);
assert(!StackEmpty(ps));
ps->top--;
}
StackDataType StackTop(Stack* ps)//取栈顶的值
{
assert(ps);
assert(!StackEmpty(ps));
return ps->arr[ps->top - 1];
}
bool StackEmpty(Stack* ps)//判断栈是否为空
{
assert(ps);
return ps->top == 0;
}
int StackSize(Stack* ps)//取栈的大小
{
assert(ps);
return ps->top;
}
二、队列:
1.队列的基本概念:
队列:只允许在一端进行插入数据操作,在另一端进行删除数据操作的特殊线性表,队列具有先进先出FIFO(First In First Out) 的存取顺序。
存取顺序:
- 队头:出队列进行删除操作的一端称为队头。
- 队尾:进行插入操作的一端称为队尾。
2.如何实现队列?
队列也可以数组结构实现,但是使用链表的结构实现更优一些,因为如果使用数组的结构,出队列在数组头上出数据,需要挪动数据,效率会比较低。
3.队列代码演示:
void QueueInit(Queue* pq)//队列初始化
{
assert(pq);
pq->head = pq->tail = NULL;
pq->size = 0;
}
void QueueDestroy(Queue* pq)//队列销毁
{
assert(pq);
QueueNode* cur = pq->head;
while (cur)
{
QueueNode* next = cur->next;
free(cur);
cur = next;
}
pq->head = pq->tail = NULL;
}
void QueuePush(Queue* pq, QueueDataType x)//队列入值
{
assert(pq);
QueueNode* newnode = (QueueNode*)malloc(sizeof(QueueNode));
if (newnode == NULL)
{
perror("malloc");
exit(-1);
}
newnode->data = x;
newnode->next = NULL;
if (pq->head == NULL)
{
pq->head = pq->tail = newnode;
}
else
{
pq->tail->next = newnode;
pq->tail = newnode;
}
pq->size++;
}
void QueuePop(Queue* pq)//队列删值
{
assert(pq);
assert(!QueueEmpty(pq));
if (pq->head->next == NULL)
{
free(pq->head);
pq->head = pq->tail = NULL;
}
else
{
QueueNode* next = pq->head->next;
free(pq->head);
pq->head = next;
}
pq->size--;
}
QueueDataType QueueFront(Queue* pq)//队列首值
{
assert(pq);
assert(!QueueEmpty(pq));
return pq->head->data;
}
QueueDataType QueueBack(Queue* pq)//队列尾值
{
assert(pq);
assert(!QueueEmpty(pq));
return pq->tail->data;
}
bool QueueEmpty(Queue* pq)//队列判空
{
return pq->head == NULL;
}
int QueueSize(Queue* pq)//队列大小
{
return pq->size;
}
总结
以上就是今天要讲栈和队列的内容,如果对刚刚阅读本篇博客的你有所帮助的话,不要忘记给博主一个三连哦!