c数据结构栈的基本操作(字符逆序输出)

线性栈

输入字符,再输出

#include "stdafx.h"

#include<stdlib.h>

#include<malloc.h>

 

#define STACK_SIZE 100

#define STACKINCREAMENT 10

#define ERROR 0

#define OK 1

#define OVERFLOW -2

 

typedef int SElemType;

typedef int Status;

typedef char CElemType;

 

//定义栈结构体

typedef struct Stack{

    SElemType *base;

    SElemType *top;

    int stacksize;

}SqStack;

 

//函数声明

Status InitStack(SqStack &S);

CElemType Push(SqStack &S, char e);

CElemType PrintfStack(SqStack S);

CElemType PopStack(SqStack &S);

Status StackLength(SqStack S);

 

int main()

{

    SqStack S;

    InitStack(S);

    int i,  n;

    char e;

    printf("请输入需要输入数字的个数n=");

    scanf_s("%d", &n);

    for (i = 0; i < n; i++)

    {

       printf("第%d个字符为:",i+1);

       scanf_s(" %c", &e);

       Push(S, e);

    }

PrintfStack(S);

}

//构建新的空栈

Status InitStack(SqStack &S)

{

    S.base = (SElemType*)malloc(STACK_SIZE*sizeof(SElemType));

    if (!S.base)

       return ERROR;

    S.top = S.base;

    S.stacksize = STACK_SIZE;

    return OK;

}

 

//入栈操作

CElemType Push(SqStack &S, char e)

{

    SElemType *p;

    if (S.top - S.base >= S.stacksize)

    {

       S.base = (SElemType*)realloc(S.base, (STACK_SIZE + STACKINCREAMENT)*sizeof(SElemType));

       if (!S.base)

           exit(OVERFLOW);

       p = S.base;

       S.top = S.base + S.stacksize;

       S.stacksize += STACKINCREAMENT;

    }

    *S.top++ = e;

    return OK;

}

 

//输出栈中存储哪些元素

CElemType PrintfStack(SqStack S)

{

    SElemType *p;

    if (S.base == S.top)

    {

       printf("The Stack is Empty!!! ");

       return 0;

    }

    printf("栈顶先输出 ");

    for (p = S.top - 1; p != S.base - 1; p--)

       printf("%c ", *p);                            //从栈顶的元素最先输出     

    printf(" ");

}

 

//出栈操作

CElemType PopStack(SqStack &S)

{

    if (S.base == S.top)

    {

       printf("The Stack is Empty!!! ");

       return OK;

    }

    printf("出栈的元素为%c ", *(S.top - 1));

    *(--S.top) = NULL;

}

 

//求栈的长度

Status StackLength(SqStack S)

{

    printf("The Stack'length is %d ! ", S.top - S.base);

    return OK;

}

原文地址:https://www.cnblogs.com/cdp1591652208/p/6202745.html