功能:入栈“123456789”并打印显示,出栈“987654321”并打印显示。
“COMMON__H”文件:
#ifndef COMMON__H
#define COMMON__H
#define TRUE 1
#define FALSE 0
#define OK 1
#define ERROR 0
#define INFEASIBLE -1
#define OVERFLOW -2
#define STACK_INIT_SIZE 100;
#define STACK_INCREMENT 10;
typedef int Status;
typedef int SELemType;
#endif
“Stack”文件:
#include <stdlib.h>
#include <stdio.h>
#include "common.h"
typedef struct
{
SELemType *base;
SELemType *top;
int stacksize;
} SqStack;
// 定义函数,用于初始化栈
Status InitStack(SqStack &S)
{
S.base = (SELemType *)malloc(100 * sizeof(SELemType));// 分配内存空间给栈的基址,并检查是否分配成功
if (!S.base)
{
exit(OVERFLOW);// 如果分配失败,则退出程序,并显示内存溢出错误
}
S.top = S.base;// 初始化栈顶指针指向栈底,表示栈为空
S.stacksize = STACK_INIT_SIZE;// 初始化栈的大小为预定义的初始大小
return OK;
}
// 定义函数,用于获取栈顶元素
Status GetTop(SqStack S, SELemType &e)// 如果栈为空,即栈顶指针等于栈底指针,则返回错误状态
{
if (S.top == S.base)
{
return ERROR;
}
e = *(S.top - 1);// 否则,将栈顶元素赋值给传入的参数e
return OK;
}
// 定义函数,执行进栈操作
Status Push(SqStack &S, SELemType e)
{
if (S.top - S.base >= S.stacksize)// 如果栈满,则需要重新分配内存空间
{
S.base = (SELemType *)realloc(S.base, (S.stacksize + 10) * sizeof(SELemType));// 重新分配内存空间,增加栈的容量
if (!S.base) exit(OVERFLOW);// 如果内存分配失败,则退出程序,表示栈上溢
S.top = S.base + S.stacksize;// 调整栈顶指针的位置和栈的大小
S.stacksize += STACK_INCREMENT;
}
*S.top++ = e; // 将新元素入栈,并将栈顶指针上移
return OK;
}
// 出栈操作
Status Pop(SqStack &S, SELemType &e)// 如果栈为空,则返回错误状态
{
if (S.top == S.base)
{
return ERROR;
}
e = *(--S.top);// 将栈顶元素出栈,并将其赋值给参数e
return OK;
}
// 销毁栈
void DestroyStack(SqStack &S)
{
free(S.base);// 释放栈的基地址所指向的内存空间
S.base = NULL;// 将栈顶指针置为NULL,表示栈已经被销毁
S.top = NULL;// 将栈的大小设置为0,表示栈已经被销毁
S.stacksize = 0;
}
//主函数
int main(void)
{
SqStack S;
SELemType e;
InitStack(S);
int i = 0;
int j = 0;
// 调用函数把20231424153每一位数字入栈
char str[] = "123456789";
printf("入栈顺序为:");
for (i ; str[i] != '\0'; ++i)// 遍历字符串中的每一位数字
{
Push(S, str[i] - '0');// 将数字字符转换为整数并入栈
printf("%d",str[i] - '0');// 打印入栈的元素
}
printf("\n");
// 调用函数所有元素出栈
printf("出栈顺序为:");
for(j ; S.top != S.base ; j++)
{
Pop(S, e);
printf("%d", e);
}
printf("\n");
DestroyStack(S);// 销毁栈
return 0;
}