#include<iostream>
using namespace std;
#include<stdlib.h>
#define OK 1
#define ERROR 0
#define OVERFLOW -2
#define MAXSIZE 10
typedef int Status;
typedef int SElemType;//给int类型取别称为SElemType
//顺序栈的定义
typedef struct
{
SElemType* base;
SElemType* top;
int stackssize;
}SqStack;
//初始化
Status Initstack(SqStack& S)
{//构造空栈S
S.base = new SElemType[MAXSIZE];//为顺序表动态分配最大容量
if (!S.base)exit(OVERFLOW);//存储分配失败
S.top = S.base;//top初始为base,空栈
S.stackssize = MAXSIZE;//栈的最大容量
return OK;
}
//入栈
Status Push(SqStack& S, SElemType e)
{//插入元素e为新的栈顶元素
if (S.top - S.base == S.stackssize)return ERROR;
*S.top++ = e;
return OK;
}
//出栈
Status Pop(SqStack& S, SElemType& e)
{//删除栈顶元素,用e返回
if (S.top == S.base)return ERROR;
e = *--S.top;
return OK;
}
int main()
{
int N,e,d;
SqStack S;
Initstack(S); //初始化一个栈,并用S保存其返回结果
cout << "shuru: " << endl;
cin >> N;
cout << "jinzhishu: " << endl;
cin >> d;
/* std::cout << "请输入需要转换的进制数: ";//重载
std::cin >> N;
std::cout << "您输入的进制数是: " << N << std::endl;
*/
while (N) //当需要转进制的数合法时,才执行循环语句
{
Push(S, N % d); //辗转相除,取余数入栈
N = N / d;
}
while (!(S.top == S.base)) //栈非空
{
Pop(S, e);//出栈
if (d <= 10)
{
cout << e;
}
else
{
if (e <= 9) cout << e;
else cout << (char)e + 55;
}
}
return 0;
}
进制转换--栈
最新推荐文章于 2024-06-17 19:20:01 发布