SqStack进制计算

基于SqStack 进制计算

#include<malloc.h> 
#include<stdio.h> 
#include<stdlib.h> 
typedef int Status;
typedef int SElemType;
#define STACK_INIT_SIZE 100 
#define STACKINCREMENT 20
#define OVERFLOW -2
#define OK 1
#define ERROR 0
typedef struct SqStack
{
    SElemType *base;
    SElemType *top;
    int stacksize;
} SqStack; // 顺序栈


Status InitStack(SqStack &S)
{ // 构造一个空栈S
    if (!(S.base = (SElemType *)malloc(STACK_INIT_SIZE * sizeof(SElemType))))
        exit(OVERFLOW); // 存储分配失败
    S.top = S.base;
    S.stacksize = STACK_INIT_SIZE;
    return OK;
}
int GetTop(SqStack S)
{ // 若栈不空,则用e返回S的栈顶元素
    if (S.top>S.base)
        return *(S.top - 1);
}

Status Push(SqStack &S, SElemType e)
{ // 插入元素e为新的栈顶元素

    if (S.top - S.base >= S.stacksize) // 栈满,追加存储空间
    {

        S.base = (SElemType *)realloc(S.base, (S.stacksize + STACKINCREMENT) * sizeof(SElemType));
        if (!S.base)
            exit(OVERFLOW); // 存储分配失败
        S.top = S.base + S.stacksize;
        S.stacksize += STACKINCREMENT;
    }
    *S.top = e;
    S.top++;
    return OK;
}

Status Pop(SqStack &S, SElemType &e)
{ // 若栈不空,则删除S的栈顶元素,用e返回其值,并返回OK;否则返回ERROR
    if (S.top == S.base)
        return ERROR;
    //e=*--S.top;//e=*S.top;
    S.top--;
    e = *S.top;
    return e;
}

Status StackTraverse(SqStack S, Status(*visit)(SElemType))
{ // 从栈底到栈顶依次对栈中每个元素调用函数visit()。
  // 一旦visit()失败,则操作失败
    while (S.top>S.base)
        visit(*S.base++);
    printf("
");
    return OK;
}
int main()
{
    SqStack S;
    int x, y, e,num1;
    InitStack(S);
    printf("输入一个十进制数:
");
    scanf("%d", &x);
    printf("输入一个进制数:
");
    scanf("%d", &num1);
    while (x)
    {
        Push(S, x % num1);
        x = x / num1;
    }
    while (S.base != S.top)
    {
        y = Pop(S, e);
        printf("%d", y);
    }
    printf("
======================
");

    system("pause");
    return 0;
}

参考:https://blog.csdn.net/sunshunli/article/details/78461172

原文地址:https://www.cnblogs.com/herd/p/11761629.html