Application of chain stack: converting decimal integers to r-ary numbers

Content : Convert the decimal integer num into r-ary number, and the conversion method is the rolling and dividing method. It is required to be implemented with a chain stack.

step:

Analysis of Algorithms:

The main function has two inputs, that is, the number to be converted and the base to be converted. The idea of ​​the Convert function is to first judge whether the number to be converted is positive or negative, and then use the if...else statement to realize the conversion of positive and negative numbers respectively. The remainder and rounding operations are implemented by means of stack operations for rolling and dividing.

Outline design:

Push() function

Implement push operation

Pop() function

Implement the stack operation

Empty() function

Empty stack judgment

Convert() function

Implement hexadecimal conversion operations

code show as below:

#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); 
 }

operation result:

 

Guess you like

Origin blog.csdn.net/weixin_54474126/article/details/121731890