C语言中的栈实现进制转换

2024-11-30 07:34:21
推荐回答(2个)
回答(1):

#include
#include
#include

#define MAXSIZE 100

typedef int DataType;
typedef struct{
DataType data[MAXSIZE];
int top;
}SeqStack,*PSeqStack;

PSeqStack Init_SeqStack(void)
{
PSeqStack S;
S=(PSeqStack)malloc(sizeof(SeqStack));
if(S)
S->top=-1;
return S;
}

int Push_SeqStack(PSeqStack S,DataType x)
{
if (S->top==MAXSIZE-1)
return 0;
else
{
S->top++;
S->data[S->top]=x;
return 1;
}
}

int Empty_SeqStack(PSeqStack S)
{
if(S->top==-1)
return 1;
else
return 0;
}

int Pop_SeqStack(PSeqStack S,DataType *x)
{
if(Empty_SeqStack(S))
return 0;
else
{
*x=S->data[S->top];
S->top--;
return -1;
}
}

void Destory_SeqStack(PSeqStack *S)
{
if(*S)
free(*S);
*S=NULL;
return;
}

typedef int DataType;
int conversation(int n,int r)
{
PSeqStack S;
DataType x;
if(!r)
{
printf("基数不能为0");
return(0);
}
S=Init_SeqStack();
if(!S)
{
printf("栈初始化失败");
return(0);
}
while(n)
{
Push_SeqStack(S,n%r);
n=n/r;
}
while (!Empty_SeqStack(S))
{
Pop_SeqStack(S,&x);
printf("%d",x);
}
Destory_SeqStack(&S);
return 0;
}

void main()
{
int i,a;
printf("输入要转换的进制!!\n");
scanf("%d",&a);
printf("输入要转换的数!!\n");
scanf("%d",&i);
conversation(i,a);
}

回答(2):

#include
#include
#include

#define MAXSIZE 100
#define DataType int //-------------------------

typedef struct {
DataType data[MAXSIZE];
int top;
}SeqStack,*PSeqStack;

PSeqStack Init_SeqStack(void)
{
PSeqStack S;
S=(PSeqStack)malloc(sizeof(SeqStack));
if(S)
S->top=-1;
return S;
}

int Push_SeqStack (PSeqStack S,DataType x) //----------------------------,
{
if (S->top==MAXSIZE-1)
return 0;
else
{
S->top++;
S->data[S->top]=x;
return 1;
}
}

int Empty_SeqStack(PSeqStack S); ////-----------------------------------------
int Pop_SeqStack(PSeqStack S,DataType *x)
{
if(Empty_SeqStack (S))
return 0;
else
{
*x=S->data[S->top];
S->top--;
return -1;
}
}

void Destory_SeqStack (PSeqStack *S)
{
if(*S)
free(*S);
*S=NULL;
return;
}

int Empty_SeqStack(PSeqStack S)
{
if(S->top==-1)
return 1;
else
return 0;
}

int conversation (int n,int r)
{
PSeqStack S;
DataType x;
if(!r)
{
printf("基数不能为0");
return(0);
}
S=Init_SeqStack();
if(!S)
{
printf("栈初始化失败");
return(0);
}
while(n)
{
Push_SeqStack(S,n%r);
n=n/r;
}
while (!Empty_SeqStack(S))
{
Pop_SeqStack(S,&x);
printf("%d",x);
}
Destory_SeqStack (&S);
}

void main()
{
int i,a;
printf("输入要转换的进制!!\n");
scanf("%d",&a);
printf("输入要转换的数!!\n");
scanf("%d",&i);
conversation(i,a);
}