文章目录
栈
1.栈的概念和结构
2.定义栈
typedef int SLDatatype;
typedef struct Stack{
SLDatatype *a;
int top;
int capacity;
}ST;
3.栈的初始化
void LNInit(ST *ps){
assert(ps);
ps->a=NULL;
ps->top=-1;//top指向栈顶元素
ps->capacity=0;
}
4.栈的销毁
void STDestroy(ST* ps)
{
assert(ps);
free(ps->a);
ps->a = NULL;
ps->top = ps->capacity = 0;
}
5.栈的插入(压栈)
void STPush(ST* ps, STDataType x)
{
assert(ps);
// ˣ
if (ps->top == ps->capacity)
{
int newcapacity = ps->capacity == 0 ? 4 : ps->capacity * 2;
STDataType* tmp = (STDataType*)realloc(ps->a, newcapacity * sizeof(STDataType));
if (tmp == NULL)
{
perror("realloc fail");
return;
}
ps->a = tmp;
ps->capacity = newcapacity;
}
ps->a[ps->top] = x;
ps->top++;
}
6.栈的删除
void STPop(ST* ps)
{
assert(ps);
assert(!STEmpty(ps));
ps->top--;
}
7.取栈顶元素
STDataType STTop(ST* ps)
{
assert(ps);
assert(!STEmpty(ps));
return ps->a[ps->top - 1];
}
8.栈的大小
int STSize(ST* ps)
{
assert(ps);
return ps->top;
}
9.判断栈是否为空
bool STEmpty(ST* ps)
{
assert(ps);
return ps->top == 0;
}
队列
1. 队列的定义和结构
2.定义队列
typedef int SLDatatype;
typedef struct QueueNode{
SLDatatype *a;
int val;
struct List*next;
}QNode;
struct Queue{
QNode*phead;
QNode*ptail;
};
3.入队列
void QueuePush(Queue*pq,QDatatype x){
assert(pq);
QNode* newnode=(QNode*)malloc(sizeof(QNode*));
if(newnode==NULL)
{
printf("malloc failed");
return;
}
if(pq->ptail){
pq->ptail->next=newnode;
pq->ptail=newnode;
}
else{
pq->phead=pq->ptail=newnode;
}
pq->size++;
}
4.出队列
void QueuePop(Queue*pq){
assert(pq);
assert(pq->phead!=NULL);
if(pq->phead==NULL){
free(pq->phead);
pq->phead=NULL;
}
else{
QNode*next=*pphead->next->val;
free(pq->pphead);
pq->phead=next;
}
pq->size--;
}
4.取队头值
QDataType QueueFront(Queue*pq){
assert(pq);
assert(pq->phead!=NULL);
return pq->phead->val;
}
5.判断是否为空
bool Empty(Queue*pq){
assert(pq);
return pq->size=0;
}