栈应用举例----数制转换
数制转换 | 整数部分
十进制整数N和其他d进制数的转换基于一下原理:
十进制->d进制:(整数部分)除基倒取余
这刚好符合栈的特性,余数后进先出,因此我们可以使用栈来进行这一转换。
设计思路
我们希望可以自己输入进制进行转换,首先,输入转换进制和转换数,入栈push函数进行存储,出栈pop函数输出。
代码实现
//
// Created by liao on 2020/10/20.
//
#include<iostream>
using namespace std;
#define MaxSize 100
typedef struct
{
int *base;
int *top;
}SqStack;
int InitStack(SqStack &S)
{
S.base=new int[MaxSize];
if(!S.base) return -1;
S.top=S.base;
return 0;
}
int PushStack(SqStack &S,int e)
{
if(S.top-S.base==MaxSize)
return -1;
*S.top++;
*S.top=e;
return 0;
}
int PopStack(SqStack &S,int &e)
{
if(S.top==S.base)
return -1;
e=*S.top;
S.top--;
return 0;
}
int StackEmpty(SqStack &S)
{
if (S.top == S.base)
return 0;
else
return -1;
}
int main()
{
int N,d;
SqStack S;
InitStack(S);
cout<<"请输入要转换的数:"<<endl;
cin>>N;
cout<<"请输入要转换的进制:"<<endl;
cin>>d;
while(N)
{
PushStack(S,N%d);
N=N/d;
}
cout<<"转换后的数为:";
while(StackEmpty(S))
{
int e;
PopStack(S,e);
cout<<e;
}
return 0;
}