栈和队列
栈
栈是一种后进先出的结构,插入数据的一端称为栈顶,另一端称为栈底。插入数据称为圧栈(入栈),栈的删除称为出栈,出栈也在栈顶进行。
数组栈的实现
#include<stdio.h>
#include<stdlib.h>
#include<assert.h>
#include<stdbool.h>
typedef int STNodeType;
typedef struct STack
{
STNodeType* _a;
int _top;
int _capacity;
}ST;
void StackInit(ST* ps)
{
assert(ps);
ps->_a = NULL;
ps->_capacity = ps->_top = 0;
}
void Push(ST* ps, STNodeType val)
{
assert(ps);
//判断是否需要扩容
if (ps->_top == ps->_capacity)
{
int newcapacity = ps->_capacity == 0 ? 4 : ps->_capacity * 2;
STNodeType* tmp = realloc(ps->_a, sizeof(STNodeType)*newcapacity);
if (tmp == NULL)
{
printf("realloc ");
exit(-1);
}
ps->_a = tmp;
ps->_capacity = newcapacity;
}
ps->_a[ps->_top] = val;
ps->_top++;
}
bool Empty(ST* ps)
{
assert(ps);
return ps->_top == 0;
}
void Pop(ST* ps)
{
assert(ps);
assert(ps->_top > 0);
ps->_top--;
}
STNodeType StackTop(ST* ps)
{
assert(ps);
assert(ps->_top > 0);
return ps->_a[ps->_top - 1];
}
void Destroy(ST* ps)
{
assert(ps);
free(ps->_a);
ps->_a = NULL;
ps->_capacity = ps->_top = 0;
}
队列
队列仅允许在一段插入数据,在另一段删除数据的受限的线性表。具有先进先出的特点;入队列的一端称为队尾,出队列的一端称为队头。
队列可以通过链表实现也可以通过数组实现,使用链表实现效率会高一些,使用数组实现在出队列时,需要挪动数据。
队列的实现(链式)
#include<stdio.h>
#include<assert.h>
#include<stdlib.h>
#include<stdbool.h>
typedef int QDateType;
typedef struct QueueNode
{
struct QueueNode* next;
QDateType _val;
}QueueNode;
typedef struct Queue
{
QueueNode* head;
QueueNode* tail;
}Queue;
void QueueInit(Queue* pq)
{
assert(pq);
pq->head = pq->tail = NULL;
}
void QueueDestory(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, QDateType val)
{
assert(pq);
QueueNode* newnode = (QueueNode*)malloc(sizeof(QueueNode));
newnode->_val = val;
newnode->next = NULL;
if (pq->head == NULL)
{
pq->tail = pq->head = newnode;
}
else
{
pq->tail->next = newnode;
pq->tail = newnode;
}
}
void QueuePop(Queue* pq)
{
assert(pq);
assert(!QueueEmpty(pq));
QueueNode* next = pq->head->next;
free(pq->head);
pq->head = next;
//如果删空了,需要将尾指针置空
if (pq->head == NULL)
pq->tail = NULL;
}
QDateType QueueFront(Queue* pq)
{
assert(pq);
assert(!QueueEmpty(pq));
return pq->head->_val;
}
QDateType QueueBack(Queue* pq)
{
assert(pq);
assert(!QueueEmpty(pq));
return pq->tail->_val;
}
bool QueueEmpty(Queue* pq)
{
assert(pq);
return pq->head == NULL;
}
size_t QueueSize(Queue* pq)
{
size_t count = 0;
QueueNode* cur = pq->head;
while (cur)
{
count++;
cur = cur->next;
}
return count;
}