广州科技网站建设,信息产业部备案网站,杭州市城乡规划局建设局官方网站,网站备案后可以改名吗1 栈
1.1栈的概念及结构
栈#xff1a;一种特殊的线性表#xff0c;其只允许在固定的一端进行插入和删除元素操作。进行数据插入和删除操作的一端称为栈顶#xff0c;另一端称为栈底。栈中的数据元素遵守后进先出LIFO#xff08;Last In First Out#xff09;的原则 压栈…
1 栈
1.1栈的概念及结构
栈一种特殊的线性表其只允许在固定的一端进行插入和删除元素操作。进行数据插入和删除操作的一端称为栈顶另一端称为栈底。栈中的数据元素遵守后进先出LIFOLast In First Out的原则 压栈栈的插入操作叫做进栈/压栈/入栈入数据在栈顶 出栈栈的删除操作叫做出栈。出数据也在栈顶
1.2栈的实现
栈的实现一般可以使用数组或者链表实现相对而言数组的结构实现更优一些。因为数组在尾上插入数据的 代价比较小 全部代码如下 特别注意 栈的特征是后进先出
#includeStack.h
void STInit(ST* ps)
{assert(ps);ps-a NULL;ps-capacity 0;ps-top 0;
}
void STDestroy(ST* ps)
{assert(ps);free(ps-a);ps-a NULL;ps-top 0;ps-capacity 0;
}
void STPush(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, sizeof(SLDataType) * NewCapacity);if (tmp NULL){perror(realloc fail);exit(-1);}ps-a tmp;ps-capacity NewCapacity;}
}
void STPop(ST* ps)
{assert(ps);assert(ps-top 0);ps-top--;
}
int STSize(ST* ps)
{assert(ps);return ps-top;
}
bool STEmpty(ST* ps)
{assert(ps);return ps-top NULL;
}#pragma once
#includestdio.h
#includeassert.h
#includestdlib.h
#includestdbool.h
//#define N 10
typedef int SLDataType;
typedef struct Stack
{SLDataType* a;int top;int capacity;
}ST;
void STInit(ST* ps);
void STDestroy(ST* ps);
void SLPush(ST* ps, SLDataType x);
void STPop(ST* ps);
int STSize(ST* ps);
bool STEmpty(ST* ps);