用栈实现数制转换

来源:互联网 发布:淘宝奢侈品代购 编辑:程序博客网 时间:2024/04/29 16:43

算法思想如下:当N>0时重复1,2

1、若 N≠0,则将N % r 压入栈s,执行2;若N=0,将栈s的内容依次出栈,算法结束。

 2、用N / r 代替 N

void conversion () {

   InitStack(S);

   scanf ("%d",N);

   while (N) {

     Push(S, N % 8);

     N = N/8;

   }

   while (!StackEmpty(S)) {

     Pop(S,e);

     printf ( "%d", e );

   }

} // conversion

 

 

网上找的不错的c语言代码。。数据结构一切从零开始,没事多敲几遍

http://zhidao.baidu.com/question/191453271.html

#include<stdio.h>
#include<malloc.h>
#include<stdlib.h>
typedef struct
{
 int *base;
 int stacksize;
 int *top;
}sqstack;
void initstack(sqstack*S)
{
 (*S).base =(int*)malloc(sizeof(int)*10);
 if(!(*S).base )exit(0);
 (*S).stacksize =10;
 (*S).top =(*S).base ;
}
int pop(sqstack*S)
{
 int e;
 if((*S).base ==(*S).top ) exit(0);
 e=*(--(*S).top);
 return e;
}
void push(sqstack *S,int e)
{
 if((*S).top -(*S).base>=(*S).stacksize )
 {
  (*S).base=(int*)realloc((*S).base ,sizeof(int)*((*S).stacksize +1));
  if(!(*S).base )exit(0);
  (*S).top =(*S).base+(*S).stacksize ;
  (*S).stacksize ++;
 }
 *(*S).top =e;
 (*S).top ++;
}
int StackEmpty(sqstack*S)
{
 if((*S).top ==(*S).base )
  return 0;
 return 1;
}
int main()
{
 int i,e,a;
 sqstack S;
 initstack(&S);
 printf("输入要转换的进制!!\n");
 scanf("%d",&a);
 printf("输入要转换的数!!\n");
 scanf("%d",&i);
 while(i)
 {
  push(&S,i%a);
  i/=a;
 }
 while(StackEmpty(&S))
 {
  e=pop(&S);
  printf("%d",e);
 }
 printf("\n");
 return 0;
}

原创粉丝点击