cpp
#include<stdio.h>
#include<stdlib.h>
//类型创建
typedef struct LinkedStackNode
{
int data;
struct LinkedStackNode* next;
}LinkedStackNode, * LinkedStack;
LinkedStack top;
//链栈的初始化
//头结点的初始化
LinkedStack Init_LinkedStack()
{
LinkedStack top = (LinkedStackNode*)malloc(sizeof(LinkedStackNode));
if (top != NULL)
{
top->next = NULL;
}
else
{
printf("头结点申请空间失败\n");
}
return top;
}
//判断栈空
int LinkedStack_Empty(LinkedStack top)
{
if (top->next == NULL)
{
return 1;
}
else
{
return 0;
}
}
//入栈
int Push_LinkedStack(LinkedStack top, int x)
{
LinkedStackNode* node;
node = (LinkedStackNode*)malloc(sizeof(LinkedStackNode));
if (node == NULL)
{
printf("节点申请空间失败\n");
return 0;
}
node->data = x;
node->next = top->next;
top->next = node;
return 1;
}
//出栈
int Pop_LinkedStack(LinkedStack top, int* x)
{
LinkedStackNode* node;
if (top->next == NULL)
{
printf("链栈为空,无法进行出栈操作\n");
return 0;
}
else
{
node = top->next;
*x = node->data;
top->next = node->next; //将头结点后的节点整体向前一位
free(node);
return 1;
}
}
//读取栈顶元素
int Get_LinkedStack(LinkedStack top, int* x)
{
if (top->next == NULL)
{
printf("链栈为空\n");
return 0;
}
else
{
*x = top->next->data;
return 1;
}
}
//对于输入的任意一个非负十进制整数,打印输出与其等值的任意进制数
void Conversion(int N)
{
int x; //声明变量x,输出转换后各个位数上的数
int jinzhi;
printf("请输入需要转换为的进制数\n");
scanf("%d",&jinzhi);
LinkedStack S = Init_LinkedStack(); //构造空链栈S
while (N > 0) //当N>0时,继续进行数值转换
{
Push_LinkedStack(S,N%jinzhi); //对N对进制数的余数的入栈
N /=jinzhi; //将N的商赋值给本身,便于下一轮计算
}
printf("转化后的进制数为:");
while (!LinkedStack_Empty(S)) //栈不为空时,出栈栈中的余数
{
Pop_LinkedStack(S,&x); //进行出栈操作
printf("%d ",x);
}
}
int main()
{
//栈的初始化
//头结点的初始化
LinkedStack top;
top = Init_LinkedStack();
if (top == NULL)
{
printf("申请链栈空间失败\n");
}
//对于输入的任意一个非负十进制整数,打印输出与其等值的任意进制数
int N;
printf("请输入需要转换的非负十进制数\n");
scanf("%d",&N);
Conversion(N);
return 0;
}