链栈的应用:十进制整数转化为r进制数

内容:将十进制整数num 转换为r进制数,其转换方法为辗转相除法。要求用链栈实现 。

步骤:

算法分析:

主函数有两个输入,即输入待转化的数和要转化的进制,Convert函数思想:先判断待转化数的正负,用if...else语句分别实现正数和负数的转化,利用取余和取整操作,再借助于栈的操作进行辗转相除来实现。

概要设计:

Push()函数

实现入栈操作

Pop()函数

实现出栈操作

Empty()函数

空栈判断

Convert()函数

实现进制转换操作

代码如下:

#include <stdio.h>
#include <stdlib.h>
typedef int datatype;
typedef struct node
{
	datatype data;
	struct node *next;
}*linkstack;
int Push(linkstack*top,datatype x)
{
	linkstack s=(linkstack)malloc(sizeof(struct node));
	if(s==NULL)
	return 0;
	s->data=x;
	s->next=(*top);
	(*top)=s;
	return 1;
}
int Empty(linkstack top)
{
	if(top==NULL)
	return 1;
 return 0;
}
int Pop(linkstack*top,datatype*x)
{
	if(top!=NULL)
	{
	linkstack p=(*top);
	(*x)=(*top)->data;
	(*top)=(*top)->next;
	free(p);
	return 1;
	}
	return 0;
}
void Convert(int num,int mode)
{int h;
linkstack top=NULL;
printf("转化结果为;");
if(num>0)
{
	while(num!=0)
	{
		h=num%mode;
		Push(&top,h);
		num=num/mode; 
	}
	while(!Empty(top))
	{
		Pop(&top,&h);
		printf("%d",h); 
	}
	printf("\n");
 } 
 else if(num<0)
 {
 	printf("-");
 	num=num*(-1);
 	while(num!=0)
 	{
 		h=num%mode;
 		Push(&top,h);
		 num=num/mode; 
	 }
	 while(!Empty(top))
	 {
	 	Pop(&top,&h);
		 printf("%d",h); 
	 }
	 printf("\n");
 }
 else
 printf("%d\n",0);
}
 void main()
 {
 	int num ,mode;
 	printf("\n 请输入要转化的数");
	 scanf("%d",&num);
	printf("请输入要转化的进制;");
	scanf("%d",&mode);
	Convert(num,mode); 
 }

运行结果:

 

猜你喜欢

转载自blog.csdn.net/weixin_54474126/article/details/121731890