您的位置:首页 > 理论基础 > 数据结构算法

【数据结构】用栈实现数制的转换

2015-11-10 15:02 423 查看


用栈实现数制的转换.cpp

#include<iostream>

using namespace std;

typedef int SElemType;

typedef struct

{

SElemType *base;

SElemType *top;

int stacksize;

}SqStack;

void InitStack(SqStack &S)//构造一个空栈

{

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

if (!S.base)

{

cout << "存储分配失败!" << endl;

exit(0);

}

S.top = S.base;

S.stacksize = 20;

}

void Push(SqStack &S, SElemType e)//进栈

{

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

{

S.base = (SElemType *)malloc((S.stacksize+10 )* sizeof(SElemType));//如果栈满,申请新空间

if (!S.base)

{

cout << "存储分配失败!" << endl;

exit(0);

}

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

S.stacksize+=10;

}

*S.top++ = e;

}

int Pop(SqStack &S, SElemType &e)//出栈

{

if (S.top == S.base) return 0;

e = *--S.top;

cout << e;

return 0;

}

void conversion()

{

SqStack S;

InitStack(S);

int N, M;

cout << "请输入要转换N的数及数制M:" << endl;

cin >> N >> M;

cout<<"将"<<N<<"转换成"<<M<<"进制后,为:"<<endl;

while (N)

{

Push(S, N%M);

N = N/M;

}

int e;

while (S.top!=S.base)

Pop(S, e);

cout<<endl;

}

int main()

{

conversion();

return 0;

}



内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: