栈:栈是一种特殊的线性表,它只能在一端进行插入和删除,插入和删除的一端叫做栈顶,另一端叫做栈底,插入叫做入栈,删除叫做出栈,因为它只能在一端进行插入和删除,所以它有着后进先出的规律。
用顺序表来实现栈
// 支持动态增长的栈
typedef int STDataType;
typedef struct Stack
{
STDataType* _a;
int _top; // 栈顶
int _capacity; // 容量
}Stack;
初始化栈
// 初始化栈
void StackInit(Stack* ps)
{
assert(ps);
ps->_a = NULL;
ps->_capacity = ps->_top = 0;
}
入栈
//入栈
void StackPush(Stack* ps, STDataType data)
{
assert(ps);
if (ps->_capacity == ps->_top)
{
int newcapacity = ps->_capacity == 0 ? 4 : 2 * ps->_capacity;
STDataType* tmp = (STDataType*)realloc(ps->_a, newcapacity * sizeof(STDataType));
if (tmp == NULL)
{
perror("realloc fail");
exit(-1);
}
ps->_a = tmp;
ps->_capacity = newcapacity;
}
ps->_a[ps->_top] = data;
ps->_top++;
}
出栈
// 出栈
void StackPop(Stack* ps)
{
assert(ps);
assert(ps->_top >= 0);
ps->_top--;
}
获取栈顶元素
// 获取栈顶元素
STDataType StackTop(Stack* ps)
{
return ps->_a[ps->_top - 1];
}
//检测栈是否为空,如果为空返回非零结果,如果不为空返回0
int StackEmpty(Stack* ps)
{
assert(ps);
if (ps->_top == 0)
return 1;
return 0;
}
获取栈中有效元素个数
//获取栈中有效元素个数
int StackSize(Stack* ps)
{
assert(ps);
return ps->_top;
}
销毁栈
//销毁栈
void StackDestroy(Stack* ps)
{
assert(ps);
free(ps->_a);
ps->_a = NULL;
ps->_top = ps->_capacity = 0;
}
队列:队列也是一种特殊线性表,只允许在一端进行插入,在另一端进行删除。插入的一端叫做队尾,删除的一端叫做队头,插入叫做入队,删除叫做出队,因为它是一端插入,另一端删除,所以它具有先进先出的规律。
用链表实现队列
链表结点
typedef struct QListNode
{
struct QListNode* _next;
QDataType _data;
}QNode;
队列
typedef struct Queue
{
QNode* _front;
QNode* _rear;
}Queue;
初始化队列
// 初始化队列
void QueueInit(Queue* q)
{
q->_rear = q->_front = NULL;
}
队尾入队列
// 队尾入队列
void QueuePush(Queue* q, QDataType data)
{
assert(q);
if (q->_rear == NULL)
{
q->_front = q->_rear = (QNode*)malloc(sizeof(QNode));
if (q->_rear == NULL)
{
perror("malloc fail");
exit(-1);
}
q->_rear->_data = data;
q->_rear->_next = NULL;
}
else
{
QNode* cur = (QNode*)malloc(sizeof(QNode));
if (cur == NULL)
{
perror("malloc fail");
exit(-1);
}
q->_rear->_next = cur;
cur->_data = data;
cur->_next = NULL;
q->_rear = cur;
}
}
队头出队列
// 队头出队列
void QueuePop(Queue* q)
{
assert(q);
assert(q->_front);
QNode* next = q->_front->_next;
free(q->_front);
q->_front = NULL;
q->_front = next;
}
获取队列头部元素
// 获取队列头部元素
QDataType QueueFront(Queue* q)
{
assert(q);
return q->_front->_data;
}
获取队列队尾元素
// 获取队列队尾元素
QDataType QueueBack(Queue* q)
{
assert(q);
return q->_rear->_data;
}
获取队列中有效元素的个数
// 获取队列中有效元素个数
int QueueSize(Queue* q)
{
assert(q);
QNode* cur = q->_front;
int count = 0;
while (cur)
{
count++;
cur = cur->_next;
}
return count;
}
检测队列是否为空,如果为空返回非零结果,如果非空返回0
// 检测队列是否为空,如果为空返回非零结果,如果非空返回0
int QueueEmpty(Queue* q)
{
assert(q);
if (q->_front == NULL)
return 1;
return 0;
}
销毁队列
// 销毁队列
void QueueDestroy(Queue* q)
{
assert(q);
QNode* cur = q->_front;
while (cur)
{
QNode* next = cur->_next;
free(cur);
cur = NULL;
cur = next;
}
}