#include<stdio.h>
#include<stdlib.h>
#include<math.h>
#include<iostream>
#include<malloc.h>
using namespace std;
#define STACK_INIT_SIZE 100
#define STACKINCREAMENT 10
typedef int SElemType;
typedef struct
{
SElemType *base;
SElemType *top;
SElemType stacksize;
}SqStack;
void InitStack(SqStack &s);
bool StackEmpty(SqStack s);
void GetTop(SqStack s,SElemType &e);
void Push(SqStack &s, SElemType e);
void Pop(SqStack &s, SElemType &e);
void conversion(SqStack &s, SElemType N, SElemType n);
void InitStack(SqStack &s)
{
s.base = (SElemType *)malloc(STACK_INIT_SIZE*sizeof(SElemType));
if (!s.base) exit(OVERFLOW);
s.top = s.base;
s.stacksize = STACK_INIT_SIZE;
}
bool StackEmpty(SqStack s)
{
if (s.base == s.top)
return true;
else
return false;
}
void GetTop(SqStack s, SElemType &e)
{
if (s.base == s.top)
return;
else
e = *(s.top - 1);
}
void Push(SqStack &s, SElemType e)
{
if (s.top - s.base >= s.stacksize)
{
s.base = (SElemType *)realloc(s.base, (s.stacksize + STACKINCREAMENT)*sizeof(SElemType));
if (!s.base) exit(OVERFLOW);
s.top = s.base + s.stacksize;
s.stacksize += STACKINCREAMENT;
}
*s.top++ = e;
}
void Pop(SqStack &s, SElemType &e)
{
if (s.base == s.top) return;
e = *--s.top;
}
void conversion(SqStack &s, SElemType N, SElemType n)
{
InitStack(s);
while (N)
{
Push(s,N%n);
N = N / n;
}
cout << "转化成" << n << "进制之后的数:";
while (!StackEmpty(s))
{
SElemType e;
Pop(s,e);
cout << e;
}
}
int main()
{
SElemType N, n;
SqStack x;
InitStack(x);
cout << " 输入需要转化的数:";
cin >> N;
cout << "输入转换的目标进制:";
cin >> n;
cout << endl;
conversion(x,N,n);
}
利用栈解决数制转换问题
最新推荐文章于 2019-08-01 21:53:22 发布