# 十进制转R进制链表（C语言）

#include <stdio.h>
#include <stdlib.h>
typedef int ElemType;
{
ElemType data;
}LiStack;

//初始化栈
void InitStack(LiStack* &s)
{
s = (LiStack *)malloc(sizeof(LiStack));
s->next = NULL;
}

//进栈
void Push(LiStack* &s,ElemType e)
{
LiStack *p;//定义一个新指针
p = (LiStack *)malloc(sizeof(LiStack));//新节点
p->data = e;
p->next = s->next;
s->next = p;
}

//出栈
void Pop(LiStack* &s,ElemType e)
{
LiStack *p=s->next;//定义一个在栈顶的指针
if(s->next == NULL)
return;
else
{
p->data =e;
s->next=p->next;
free(p);
return;
}
}
//遍历
void StackTraverse(LiStack* &s)
{
LiStack *p=s->next;
while(p !=NULL)
{
printf("%d ",p->data);
p=p->next;
}
printf("\n");
}
//获得栈顶元素
bool GetTop(LiStack* &s,ElemType &e)
{
LiStack *p=s->next;
if(s->next == NULL)
return false;
e=p->data;
return true;
}
//判断是否为空
void StackEmpty(LiStack* &s)
{
if(s->next==NULL)
printf("栈空");
else
{
printf("栈为:\n");
StackTraverse(s);
}
}
//清空栈
void ClearStack(LiStack* &s)
{
s->next=NULL;
printf("已清空\n");
}
//销毁栈
void Destroy(LiStack* &s)
{
LiStack *p=s->next,*q=s;
while(p!=NULL)
{
free(q);
q=p;
p=p->next;
}
free(p);
}
int main()
{
LiStack a;
LiStack *s = &a;
int m,num,t;
InitStack(s);
ElemType e;
while(1)
{
printf("1；进行进制转换，2；清空，3：销毁并退出\n");
scanf("%d",&t);
switch(t)
{
case 1: printf("请输入一个十进制的正整数：");
scanf("%d",&num);
int X;
printf("请输入要转换的进制：");
scanf("%d",&X);
while(num != 0)
{
m=num%X;
Push(s,m);
num/= X;
}
printf("对应的%d进制为：",X);
while(s->next != NULL)
{
GetTop(s,e);
printf("%d",e);
Pop(s,e);
}
printf("\n");
break;
case 2: ClearStack(s);
break;
case 3: Destroy(s);
printf("已销毁\n");
exit(0);
default:    printf("error\n");
}
}
}