#include <stdio.h>
#include <iostream>
using namespace std;
#define sElemType int
typedef struct linkNode{
sElemType data;//数据域
linkNode *next;//指针域
}*linkStack;
//判空函数(链栈为空返回1;不为空返回0)
int isEmpty(linkStack top){
return top==NULL;
}
//初始化链栈
void initLinkStack(linkStack &top){
top=NULL;
}
//插入元素到链栈
void push(linkStack &top,sElemType val){
linkStack newNode=new linkNode[1];
newNode->data=val;
newNode->next=top;
top=newNode;
}
//删除链栈的栈顶元素
void pop(linkStack &top,sElemType &val){
if(isEmpty(top)){
return;
}
val=top->data;
linkStack tempPtr=top;
top=top->next;
delete tempPtr;
}
//进制转化
void radixConvert(int num,int radix){
linkStack top;
initLinkStack(top);
while(num){
push(top,num%radix);
num=num/radix;
}
while(!isEmpty(top)){
sElemType val;
pop(top,val);
cout<<val;
}
}
int main(){
cout<<"29的二进制数为:";
radixConvert(29,2);
cout<<endl;
cout<<"29的四进制数为:";
radixConvert(29,4);
cout<<endl;
cout<<"29的八进制数为:";
radixConvert(29,8);
cout<<endl;
return 0;
}在这里插入代码片
运行结果截图如下: