写一个程序,将输入的十进制数据M 转换为八进制数据M8,将其调试通过。
在此基础上修改程序,实现十进制数据M 向N 进制(2或8或16)的转换。
(1)采用顺序存储结构实现栈。
#include<stdio.h>
#include<stdlib.h>
#include<process.h>
#define STACK_INIT_SIZE 100
#define status int
#define SElem int
#define ERROR 0
#define OK 1
typedef struct
{
SElem *base;
SElem *top;
int stacksize;
} SqStack;
void Init_SqStack(SqStack &S)
{
S.base=(SElem *)malloc(STACK_INIT_SIZE*sizeof(SElem));
if(!S.base)exit(1);
S.top=S.base;
S.stacksize=STACK_INIT_SIZE;
}
status Gettop_SqStack(SqStack S,SElem &e)
{
if(S.base==S.top) return ERROR;
else e=*(S.top-1);
return OK;
}
status Push_SqStack(SqStack &S,SElem e)
{
if(S.top-S.base==S.stacksize)
{
S.base=(SElem *)realloc(S.base,(S.stacksize+10)*sizeof(SElem));
if(!S.base) return ERROR;
S.top==S.base+S.stacksize;
}
else *S.top++=e;
return OK;
}
status Pop_SqStack(SqStack &S,SElem &e)
{
if(S.base==S.top) return ERROR;
else e=*(--S.top);
return OK;
}
status Empty_SqStack(SqStack S)
{
if(S.base==S.top) return true;
else return false;
}
void conversion()
{
SqStack S;
SElem e;
int N;
Init_SqStack(S);
printf("请输入十进制数:");
scanf("%d",&N);
while(N)
{
Push_SqStack(S,N%8); //将输入的十进制数除以8的余数入栈
N=N/8; //商赋给N
}
printf("转换为八进制为:");
while(!Empty_SqStack(S))
{
Pop_SqStack(S,e);
printf("%d",e);
}
printf("\n");
}
int main()
{
conversion();
}
代码运行效果图
(2)采用链表结构实现栈。
#include <stdio.h>
#include <malloc.h>
#include <math.h>
typedef struct Qnode //队列结点
{
int data;
struct Qnode *next;
} QNode, *QueuePtr;
typedef struct
{
QueuePtr front; //队头指针
QueuePtr rear; //队尾指针
} LinkQueue;
void QueueTraverse (LinkQueue Q) //遍历显示队列
{
QueuePtr p;
for(p=Q.front->next; p!=Q.rear; p=p->next)
printf("%d ",p->data);
printf("%d ",p->data);
}
int main()
{
LinkQueue Q;
int e,m[100],i;
QueuePtr p;
Q.front=Q.rear=(QueuePtr) malloc(sizeof(QNode)); //初始化链队列
Q.front->next=NULL; //初始化结束
printf("请输入要转化的十进制数字,并以-1结尾:\n");
scanf("%d",&e); //入队列
while(e!=-1)
{
p=(QueuePtr)malloc(sizeof(QNode));
p->data=e;
p->next=NULL;
Q.rear->next=p;
Q.rear=p;
scanf("%d",&e);
} //入队列结束
printf("十进制数字为:\n");
QueueTraverse(Q);
printf("\n");
printf("转换为八进制后变为:\n");
p=Q.front->next; //转换数制
do
{
e=p->data;
i=0;
while(e>=8) //修改数制改变这里
{
m[i]=e%8; //修改数制改变这里
e=e/8; //修改数制改变这里
i++;
}
m[i]=e;
for(; i>=0; i--)
printf("%d",m[i]);
printf("\n");
p=p->next;
}
while(p!=Q.rear);
e=p->data;
i=0;
while(e>=8) //修改数制改变这里
{
m[i]=e%8; //修改数制改变这里
e=e/8; //修改数制改变这里
i++;
}
m[i]=e;
for(; i>=0; i--)
printf("%d",m[i]); //转换结束
printf("\n");
while(Q.front) //销毁队列
{
Q.rear=Q.front->next;
free(Q.front);
Q.front=Q.rear;
} //销毁结束
}
代码运行效果图
版权声明:本文为yxy602843889原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。