Home 数据结构及算法 Stack

#include <iostream>
#include <stdio.h>
#include <stdlib.h>

#define ElemType int

using namespace std;

typedef struct
{
    ElemType *top;
    ElemType *base;
    int Stacksize;
} Stack;

bool InitStack(Stack &S)
{
    if((S.base=(ElemType *)malloc(5*sizeof(ElemType)))==NULL) return false;
    S.top=S.base;
    S.Stacksize=5;
    return true;
}

bool Push(Stack &S,ElemType e)
{
    if(S.top-S.base==S.Stacksize-1)
    {
        if((S.base=(ElemType *)realloc(S.base,++S.Stacksize*sizeof(ElemType)))==NULL)
            return false;
        S.top=S.base+S.Stacksize-2;
    }
    *S.top++=e;
    return true;
}

bool Pop(Stack &S,ElemType &e)
{
    if(S.top-S.base==0) return false;
    e=*–S.top;
    return true;
}

bool StackEmpty(Stack &S)
{
    if(S.top-S.base==0) return true;
    return false;
}

int main()
{
    Stack S;
    ElemType e;
    int decimal,radix;

    if(!InitStack(S)) return -1;
    cout <<“请输入十进制整数和要转换的进制:”;
    if(scanf(“%d%d”,&decimal,&radix)!=2) return -1;

    while (decimal)
    {
        Push(S,decimal%radix);
        decimal/=radix;
    }

    while(!StackEmpty(S))
    {
        Pop(S,e);
        cout <<e;
    }
    cout <<endl;

    return 0;
}

打赏
0 comment

You may also like

Leave a Comment

*

code