目录
栈
初始化
销毁
入栈
出栈
获取栈顶元素
判断栈是否为空
栈的大小
队列
初始化
销毁
入队列
出队列
取队头
取队尾
判空
队列长度
栈
1.初始化
//初始化
void StackInit(ST*ps)
{
ps->a = NULL;
ps->capacity = 0;
ps->top = 0;
}
2.销毁
void StackDestroy(ST*ps)
{
free(ps->a);
ps->a = NULL;
ps->capacity = 0;
ps->top = 0;
}
3.入栈
void StackPush(ST*ps, SDataType x)
{
assert(ps);
if (ps->top == ps->capacity)
{
int newcapacity = ps->capacity == 0 ? 4 : ps->capacity * 2;
SDataType*tmp = (SDataType*)realloc(ps->a, newcapacity*(sizeof(SDataType)));
assert(tmp);
ps->a = tmp;
ps->capacity = newcapacity;
}
ps->a[ps->top] = x;
ps->top++;
}
4.出栈
void StackPop(ST*ps)
{
assert(ps);
assert(!StackEmpty(ps));
ps->top--;
}
5.判空
bool StackEmpty(ST*ps)
{
assert(ps);
return ps->top == 0;
}
6.栈顶元素
SDataType StackFront(ST*ps)
{
assert(ps);
assert(!StackEmpty(ps));
return ps->a[ps->top - 1];
}
7.栈大小
int StackSize(ST*ps)
{
assert(ps);
assert(!StackEmpty(ps));
return ps->top;
}
队列
1.初始化
void QueueInit(Queue*pq)
{
assert(pq);
pq->head = pq->tail = NULL;
}
2.销毁
void QueueDestroy(Queue*pq)
{
QNode*cur = pq->head;
while (cur)
{
QNode*next = cur->next;
free(cur);
cur = next;
}
pq->head = pq->tail = NULL;
}
3.入队列
void QueuePush(Queue*pq, QDataType x)
{
assert(pq);
QNode*newnode = (QNode*)malloc(sizeof(QNode));
assert(newnode);
newnode->next = NULL;
newnode->data = x;
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
{
QNode*next = pq->head->next;
free(pq->head);
pq->head = next;
}
}
5.判空
bool QueueEmpty(Queue*pq)
{
assert(pq);
return pq->head == NULL;
}
6.获取队头
QDataType QueueTop(Queue*pq)
{
assert(pq);
return pq->head->data;
}
7.获取队尾
//获取队尾
QDataType QueueBack(Queue*pq)
{
return pq->tail->data;
}
8.队列长度
//队列长度
int QueueSize(Queue*pq)
{
QNode*cur = pq->head;
int size = 0;
while (cur)
{
size++;
cur = cur->next;
}
return size;
}