测试截图:
源代码:
//测试环境:VS2015
#include "stdafx.h"
#include<stdlib.h>
#include<stdio.h>
#define STACK_INIT_SIZE 100
#define STACKCREMENT 10
#define OK 1
#define ERROR 0
#define OVERFLOW -2
typedef struct
{
int *top;
int *base;
int stackSize;
}SqStack;
int initStack(SqStack &S)
{
//建立空栈
S.base = (int *)malloc(STACK_INIT_SIZE * sizeof(SqStack));
S.top = S.base;
S.stackSize = STACK_INIT_SIZE;
return OK;
}
//释放栈
int destroyStack(SqStack &S)
{
free(S.base);
S.base = NULL;
S.top = NULL;
S.stackSize = 0;
return OK;
}
//清空栈
int clearStack(SqStack &S)
{
if (S.top == S.base)return OK;
S.top = S.base;
return OK;
}
//入栈
int push(SqStack &S, int e)
{
if ((S.top - S.base) == S.stackSize)
{
S.base = (int *)realloc(S.base, (S.stackSize + STACKCREMENT) * sizeof(SqStack));
if (!S.base)exit(OVERFLOW);
S.top = S.base + S.stackSize;
S.stackSize += STACKCREMENT;
}
*S.top++ = e;
return OK;
}
int getTop(SqStack S, int &e)
{
if (S.top == S.base)return ERROR;
e = *--S.top;
return OK;
}
int pop(SqStack &S, int &e)
{
if (S.top == S.base)return ERROR;
e = *--S.top;
return OK;
}
int stackEmpty(SqStack S)
{
return S.top == S.base;
}
int visit(int e)
{
printf("%d ", e);
return OK;
}
int stackTraverse(SqStack S, int(*visit)(int))
{
if (S.top == S.base)
{
printf("栈中没有元素\n");
return ERROR;
}
while (S.top > S.base)
{
visit(*S.base++);
}
return OK;
}
int stackLength(SqStack S)
{
return S.top - S.base;
}
int main()
{
//基于算法N=(N div d) * d + N % d (N是十进制数,d为其他进制数,div:整除,%:求余)
//支持由十进制到2--10进制的转换,不支持浮点型
SqStack S;
initStack(S);
printf("请输入进制:");
int d;
scanf_s("%d", &d);
printf("十进制数:");
int N;
scanf_s("%d", &N);
while (N)
{
push(S, N%d);
N /= d;
}
printf("输出转换后的数:");
while (!stackEmpty(S))
{
int e;
pop(S, e);
printf_s("%d", e);
}
printf("\n");
return 0;
}