如题所述
第1个回答 推荐于2016-09-10
#include<stdio.h>
#include<stdlib.h>
#define initsize 20
#define increment 10
typedef char elemtype;
typedef struct stack{
elemtype *base;
elemtype *top;
int stacksize;
}stack;
void initstack(stack &s)//初始化栈
{s.base=(elemtype *)malloc(initsize*sizeof(elemtype));
if(!s.base)
exit(0);
s.stacksize=initsize;
s.top = s.base;}
void push(stack &s,elemtype e)//入栈,栈满则追加栈空间
{if(s.top-s.base>=initsize)
s.base=(elemtype *)realloc(s.base,(s.stacksize+increment)*sizeof(elemtype));
if(!s.base)
exit(0);
s.stacksize+=increment;
*s.top=e;
s.top++;
}
void pop(stack &s,elemtype &e)//出栈
{if(s.base==s.top)
printf("有错误");
else
e=*--s.top;
}
int empty(stack &s)//判栈空
{if(s.base==s.top)
return 1;
else return 0;
}
void clear(stack &s)
{if(s.base==s.top)
return ;
s.base=s.top;
}
void conversion(int n,int N)//进制转换
{int c;
char e;
stack s;
initstack(s);
while(n!=0)
{c=n%N;
n=n/N;
if(c<10)
*s.top++='0'+c;
else
{*s.top++='A'+c-10;
}
}
while(!empty(s))
{pop(s,e);
printf("%c",e);
}
clear(s);
}
void main()
{
int n,N;
printf("请输入十进制数:");
scanf("%d",&n);
printf("请输入需要转化进制:");
scanf("%d",&N);
printf("转化后的数是:");
conversion(n,N);
}本回答被提问者和网友采纳
#include<stdlib.h>
#define initsize 20
#define increment 10
typedef char elemtype;
typedef struct stack{
elemtype *base;
elemtype *top;
int stacksize;
}stack;
void initstack(stack &s)//初始化栈
{s.base=(elemtype *)malloc(initsize*sizeof(elemtype));
if(!s.base)
exit(0);
s.stacksize=initsize;
s.top = s.base;}
void push(stack &s,elemtype e)//入栈,栈满则追加栈空间
{if(s.top-s.base>=initsize)
s.base=(elemtype *)realloc(s.base,(s.stacksize+increment)*sizeof(elemtype));
if(!s.base)
exit(0);
s.stacksize+=increment;
*s.top=e;
s.top++;
}
void pop(stack &s,elemtype &e)//出栈
{if(s.base==s.top)
printf("有错误");
else
e=*--s.top;
}
int empty(stack &s)//判栈空
{if(s.base==s.top)
return 1;
else return 0;
}
void clear(stack &s)
{if(s.base==s.top)
return ;
s.base=s.top;
}
void conversion(int n,int N)//进制转换
{int c;
char e;
stack s;
initstack(s);
while(n!=0)
{c=n%N;
n=n/N;
if(c<10)
*s.top++='0'+c;
else
{*s.top++='A'+c-10;
}
}
while(!empty(s))
{pop(s,e);
printf("%c",e);
}
clear(s);
}
void main()
{
int n,N;
printf("请输入十进制数:");
scanf("%d",&n);
printf("请输入需要转化进制:");
scanf("%d",&N);
printf("转化后的数是:");
conversion(n,N);
}本回答被提问者和网友采纳
第2个回答 2010-12-02
小弟我喜欢C语言,但是是自学所以没学过数据结构,如果不用栈实现,小弟我可以马上给你写出来