链栈的初始化,入栈,出栈,取栈顶元素算法实现的程序
时间: 2023-06-06 16:04:51 浏览: 57
非常感谢您的提问!以下是链栈的初始化、入栈、出栈、取栈顶元素的算法实现的程序:
#define STACK_INIT_SIZE 100
#define STACKINCREMENT 10
typedef struct{
ElemType *base;
ElemType *top;
int stacksize;
}Stack;
//初始化栈
void InitStack(Stack &S){
S.base = (ElemType *)malloc(STACK_INIT_SIZE * sizeof(ElemType));
if(!S.base) exit(0);
S.top = S.base;
S.stacksize = STACK_INIT_SIZE;
}
//进栈操作
void Push(Stack &S, ElemType e){
if(S.top - S.base >= S.stacksize){
S.base = (ElemType *)realloc(S.base, (S.stacksize + STACKINCREMENT) * sizeof(ElemType));
if(!S.base) exit(0);
S.top = S.base + S.stacksize;
S.stacksize += STACKINCREMENT;
}
*S.top++ = e;
}
//出栈操作
void Pop(Stack &S, ElemType &e){
if(S.top == S.base) exit(0);
e = *--S.top;
}
//获取栈顶元素
ElemType GetTop(Stack S){
if(S.top != S.base) return *(S.top - 1);
else exit(0);
}
注意:以上代码仅供参考,具体实现需要根据具体需求进行优化和修改。