您的位置:首页 > 其它

栈在数制转换中的应用

2017-09-24 00:04 274 查看
#include <stdio.h>
#define MAX_STACK_SIZE 100
#define ERROR 0
#define OK 1
typedef int ElemType;
typedef int Status;
typedef struct Stack_Node
{
ElemType data;
struct Stack_Node *next;
}Stack_Node;
//栈的初始化
Stack_Node *Init_LInk_Stack(void)
{
Stack_Node *top;
top = (Stack_Node *)malloc(sizeof(Stack_Node));
top->next = NULL;
return (top);
}
//入栈
Status push(Stack_Node *top,ElemType e)
{
Stack_Node *p;
p = (Stack_Node *)malloc(sizeof(Stack_Node));
if(!p)
return ERROR;
p->data = e;
p->next = top->next;
top->next = p;   //钩链
return OK;
}
//弹栈(元素出栈)将元素顶出栈
Status pop(Stack_Node *top,ElemType *e)
{
Stack_Node *p;
if(top->next==NULL)
return ERROR;
p=top->next;
e = p->data;
printf("%ld",e);  //输出栈顶
top->next = p->next;
free(p);
}
//数制转换(将十进制转化为d(2或8)进制数
void conversion(int n,int d)
{
Stack_Node *S;
int k,*e;
S = Init_LInk_Stack();
while(n>0)
{
k = n%d;
push(S,k);
n = n/d;
}
while(S->next!=0)  //栈不空的时候出栈
{
pop(S,e);
}
}
int main()
{
int n;
int d;
printf("请输入十进制的数:");
scanf("%d",&n);
printf("请输入所要转化成的进制数:");
scanf("%d",&d);
conversion(n,d);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: