Files
Data-Structure/CLion/ExerciseBook/04.14/SqStack.c
2019-11-12 23:47:30 +08:00

90 lines
1.8 KiB
C
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/*=========================
* 栈的顺序存储结构(顺序栈)
==========================*/
#include "SqStack.h" //**▲03 栈和队列**//
/*
* 初始化
*
* 构造一个空栈。初始化成功则返回OK否则返回ERROR。
*/
Status InitStack(SqStack* S) {
if(S == NULL) {
return ERROR;
}
(*S).base = (SElemType*) malloc(STACK_INIT_SIZE * sizeof(SElemType));
if((*S).base == NULL) {
exit(OVERFLOW);
}
(*S).top = (*S).base;
(*S).stacksize = STACK_INIT_SIZE;
return OK;
}
/*
* 取值
*
* 返回栈顶元素并用e接收。
*/
Status GetTop(SqStack S, SElemType* e) {
if(S.base == NULL || S.top == S.base) {
return ERROR;
}
// 不会改变栈中元素
*e = *(S.top - 1);
return OK;
}
/*
* 入栈
*
* 将元素e压入到栈顶。
*/
Status Push(SqStack* S, SElemType e) {
if(S == NULL || (*S).base == NULL) {
return ERROR;
}
// 栈满时,追加存储空间
if((*S).top - (*S).base >= (*S).stacksize) {
(*S).base = (SElemType*) realloc((*S).base, ((*S).stacksize + STACKINCREMENT) * sizeof(SElemType));
if((*S).base == NULL) {
exit(OVERFLOW); // 存储分配失败
}
(*S).top = (*S).base + (*S).stacksize;
(*S).stacksize += STACKINCREMENT;
}
// 进栈先赋值,栈顶指针再自增
*(S->top++) = e;
return OK;
}
/*
* 出栈
*
* 将栈顶元素弹出并用e接收。
*/
Status Pop(SqStack* S, SElemType* e) {
if(S == NULL || (*S).base == NULL) {
return ERROR;
}
if((*S).top == (*S).base) {
return ERROR;
}
// 出栈栈顶指针先递减,再赋值
*e = *(--(*S).top);
return OK;
}