《数据结构(严蔚敏版)》学习笔记(三)——栈实现数制转换
当S.top == S.base 时,栈为空;
当S.top - S.base >= S.stacksize 时,栈空间满;
转换原理:N = (N div d) * d + N mod d;
N N div 8 N mod 8
1348 168 4
168 21 0
21 2 0
2 0 2
如下代码为10进制转8进制程序:
<span style="font-size:14px;">/*------$栈的应用——数制转换$-------*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
//初始定义
typedef int ElemType;
#define MAX_SIZE 100
typedef int Status;
#define OVERFLOW -1
#define OK 1
#define ERROR 0
#define TRUE 1
#define FALSE 0
/*动态顺序栈-SqStack*/
typedef struct{
ElemType *base;
ElemType *top;
int stacksize;
}SqStack;
</span>
<span style="font-size:14px;">//初始化栈
Status InitStack(SqStack &S)
{
if(!(S.base = (ElemType *)malloc(MAX_SIZE * sizeof(ElemType)))) exit(OVERFLOW);
S.top = S.base;
S.stacksize = MAX_SIZE;
return OK;
}
Status Pop(SqStack &S,ElemType &e)
{
if(S.top == S.base) return ERROR;
e = * --S.top;
return OK;
}
Status Push(SqStack &S,ElemType e)
{
if(S.top - S.base >= S.stacksize){
S.base = (ElemType *)realloc(S.base,(S.stacksize + MAX_SIZE) * sizeof(ElemType));
if(!S.base) exit(OVERFLOW);
S.top = S.base + S.stacksize;
S.stacksize += MAX_SIZE;
}
*S.top++ = e;
return OK;
}
Status StackEmpty(SqStack S)
{
if(S.base == S.top)
return TRUE;
else
return FALSE;
}
/*算法[非负十进制数,转化成八进制数]*/
void NumeralTrans()
{
int N;
ElemType e;
SqStack S;
InitStack(S);
scanf("%d",&N); </span><pre name="code" class="cpp"><span style="white-space:pre"> </span>while(N){
Push(S,N % 8);
N = N/8;
}
while(!StackEmpty(S)){
Pop(S,e);
printf("%d",e);
}
}int main(){NumeralTrans();printf("\n");return 0;}
栈中存余数,N替换为商
出栈后即为转制后的数
<span style="white-space:pre"> </span>while(N){
Push(S,N % 8);
N = N/8;
}
while(!StackEmpty(S)){
Pop(S,e);
printf("%d",e);
}