一. 栈
1.栈的概念及结构
栈:一种特殊的线性表,其只允许在固定的一端进行插入和删除元素操作。进行数据插入和删除操作的一端称为栈顶,另一端称为栈底。栈中的数据元素遵守后进先出LIFO(Last In First Out)的原则。
压栈:栈的插入操作叫做进栈/压栈/入栈,入数据在栈顶。
出栈:栈的删除操作叫做出栈。出数据也在栈顶。
2.栈的实现
栈的实现一般可以使用数组或者链表实现,相对而言数组的结构实现更优一些。因为数组在尾上插入数据的代价比较小。
(1)栈的定义
typedef int SDataType;
typedef struct Stack
{
SDataType* data;
int top;
int capacity;
}ST;
(2)栈的初始化
void STInit(ST* st)
{
assert(st);
st->data = (SDataType*)malloc(sizeof(SDataType) * 3);
st->top = 0;
st->capacity = 3;
}
(3)入栈
void STPush(ST* st, SDataType x)
{
assert(st);
if (st->top == st->capacity)
{
SDataType* tmp = (SDataType*)realloc(st->data, sizeof(SDataType) * st->capacity * ;
if (tmp == NULL)
{
perror("realloc");
exit(-1);
}
st->data = tmp;
st->capacity *= 2;
}
st->data[st->top] = x;
st->top++;
}
(4)判断栈是否为空
bool STEmpty(ST* st)
{
assert(st);
return st->top == 0;
}
(5)出栈
void STPop(ST* st)
{
assert(st);
assert(!STEmpty(st));
st->top--;
}
(6)栈中有效元素的个数
int STSize(ST* st)
{
return st->top;
}
(7)获取栈顶元素
StDataType STTop(ST* st)
{
assert(st);
assert(!STEmpty(st));
return st->data[st->top - 1];
}
(8)销毁栈
void STDestroy(ST* st)
{
free(st->data);
st->top = st->capacity = 0;
}
二. 队列
1.队列的概念及结构
队列:只允许在一端进行插入数据操作,在另一端进行删除数据操作的特殊线性表,队列具有先进先出FIFO(First In First Out)
入队列:进行插入操作的一端称为队尾
出队列:进行删除操作的一端称为队头
2.队列的实现
队列也可以数组和链表的结构实现,使用链表的结构实现更优一些,因为如果使用数组的结构,出队列在数组头上出数据,效率会比较低
(1)队列的定义
typedef int QDataType;
typedef struct QueueNode
{
QDataType data;
struct QueueNode* next;
}QueueNode;
typedef struct Queue
{
QueueNode* head;
QueueNode* tail;
}Queue;
(2)队列的初始化
void QueueInit(Queue* pq)
{
assert(pq);
pq->head = pq->tail = NULL;
}
(3)队尾入数据
void QueuePush(Queue* pq, QDataType 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;
}
}
(4)队头出数据
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;
}
}
(5)判断队列是否为空
bool QueueEmpty(Queue* pq)
{
assert(pq);
return pq->head == NULL;
}
(6)获取队头数据
QDataType QueueFront(Queue* pq)
{
assert(pq);
return pq->head->data;
}
(7)获取队尾数据
QDataType QueueBack(Queue* pq)
{
assert(pq);
return pq->tail->data;
}
(8)获取队列中有效元素个数
int QueueSize(Queue* pq)
{
assert(pq);
QueueNode* cur = pq->head;
int size = 0;
while (cur)
{
size++;
cur = cur->next;
}
return size;
}
(9)销毁队列
void QueueDestroy(Queue* pq)
{
assert(pq);
while (pq->head)
{
QueueNode* cur = pq->head->next;
free(pq->head);
pq->head = cur;
}
pq->head = pq->tail = NULL;
}