堆栈应用之进制转换
最近数据结构开始接触链表,堆栈,队列等,刚开始觉得好无聊,它们差不多,也没什么用处,,,不过今天看到了几个堆栈的应用,还挺有意思的…
C语言代码如下:
#include<stdio.h>
#include<stdlib.h>
typedef struct
{
int data[100];
int top;
}sqstack;
sqstack stack;
void initstack()
{
stack.top = -1;
}
void push(int n)
{
if(stack.top >= 99)
{
printf("超出转换范围\n");
exit(-1);
}
else
{
stack.top++;
stack.data[stack.top] = n;
}
}
int pop()
{
if (stack.top != -1)
{
int temp = stack.data[stack.top];
stack.top-;
return temp;
}
else
{
printf("出现错误");
exit(-1);
}
}
void conversion()
{
int n,e,m;
initstack();
printf("输入要转换的数\n");
scanf("%d",&n);
printf("要转化几进制\n");
scanf("%d",&m);
while(n)
{
push(n%m);
n=n/m;
}
while(stack.top>=0)
{
e=pop();
printf("%d",e);
}
}
int main(int argc, char **argv)
{
conversion();
return 0;
}
#include<stdlib.h>
typedef struct
{
int data[100];
int top;
}sqstack;
sqstack stack;
void initstack()
{
stack.top = -1;
}
void push(int n)
{
if(stack.top >= 99)
{
printf("超出转换范围\n");
exit(-1);
}
else
{
stack.top++;
stack.data[stack.top] = n;
}
}
int pop()
{
if (stack.top != -1)
{
int temp = stack.data[stack.top];
stack.top-;
return temp;
}
else
{
printf("出现错误");
exit(-1);
}
}
void conversion()
{
int n,e,m;
initstack();
printf("输入要转换的数\n");
scanf("%d",&n);
printf("要转化几进制\n");
scanf("%d",&m);
while(n)
{
push(n%m);
n=n/m;
}
while(stack.top>=0)
{
e=pop();
printf("%d",e);
}
}
int main(int argc, char **argv)
{
conversion();
return 0;
}
如果数字的长度超过30,也就是超过unsigned long int的最大值,该怎么做?