栈:限制仅在表的一端(表尾)进行操作(插入和删除)的线性表,是一种后进先出(Last in First Out)的数据结构,简称 LIFO。
栈的定义:
typedef char SLDataType;//栈的数据类型
typedef struct Stack {
SLDataType* a;
int top;//栈顶在数组中的下标位置
int capacity;//容量(栈的大小)
}ST;
栈的功能实现:
void StackInit(ST* ps)//对栈进行初始化
{
assert(ps);
ps->a = NULL;
ps->top = 0;
ps->capacity = 0;
}
void StackPush(ST* ps, SLDataType x)//栈的插入
{
assert(ps);
if (ps->top == ps->capacity)//扩容
{
int newcapacity = ps->capacity == 0 ? 4 : ps->capacity * 2;
SLDataType* tmp = (SLDataType*)realloc(ps->a, newcapacity*sizeof(SLDataType));
if (tmp == NULL)
{
printf("realloc fail");
exit(-1);
}
ps->a = tmp;
ps->capacity = newcapacity;
}
ps->a[ps->top] = x;
ps->top++;
}
void StackPop(ST* ps)//删除
{
assert(ps);
assert(!StackEmpty(ps));
ps->top--;
}
SLDataType StackTop(ST* ps)//查找栈顶
{
assert(ps);
return ps -> a[ps->top-1];
}
int StackSize(ST* ps)//栈的大小
{
assert(ps);
return ps->top;
}
bool StackEmpty(ST* ps)//判断栈是否为空
{
return ps->top == 0;
}
void StackDestroy(ST* ps)//栈的销毁
{
assert(ps);
free(ps->a);
ps->a = NULL;
ps->top = 0;
ps->capacity = 0;
}
队列:限制仅在一端进行插入操作,在另一端进行删除操作的线性表,是一种先进先出(First in First Out)的数据结构,简称 FIFO。
队列的定义:
typedef int QueueDataType;//队列的数据类型
typedef struct QueueNode {
QueueDataType data;
struct QueueNode* next;
}QNode;
typedef struct Queue {
QNode* head;//队头
QNode* tail;//队尾
}Queue;
队列的功能实现:
void QueueInit(Queue* pq)//初始化
{
assert(pq);
pq->head = NULL;
pq->tail = NULL;
}
void QueuePush(Queue* pq, QueueDataType x)//插入
{
assert(pq);
QNode* newnode = (QNode*)malloc(sizeof(QNode));
if (newnode == NULL)
{
printf("malloc fail");
return;
}
newnode->data = x;
newnode->next = NULL;
QNode* cur = pq->tail;
if (pq->head == NULL)
{
pq->head = pq->tail = newnode;
return;
}
cur->next = newnode;
pq->tail = cur->next;
}
void QueuePop(Queue* pq)//删除
{
assert(pq);
assert(!QueueEmpty(pq));
QNode* next = pq->head->next;
free(pq->head);
pq->head = next;
if (pq->head == NULL)
{
pq->tail = NULL;
}
}
bool QueueEmpty(Queue* pq)//判空
{
assert(pq);
return pq->head == NULL;
}
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;
}
int Queuesize(Queue* pq)//队列大小
{
assert(pq);
QNode* cur = pq->head;
int size = 0;
while (cur)
{
size++;
cur = cur->next;
}
return size;
}
void QueueDestroy(Queue* pq)//销毁
{
assert(pq);
QNode* cur = pq->head;
while (cur != NULL)//释放每个队列空间
{
QNode* next = cur->next;
free(cur);
cur = next;
}
pq->head = pq->tail = NULL;//防止出现野指针
}