数据结构的作业,顺便就放上来吧
题目: 2/8进制转换器
编写程序,从终端输入一串0/1表示二进制数,以“#”结束,输出它的8进制表示形式。要求:采用栈来实现
#include#include #define ERROR 0#define OK 1typedef struct node{ int data; struct node* nextPtr;}Stack,*LinkStack;int StackDel(LinkStack &s){ if (NULL == s) return ERROR;//判断栈是否出现了意外的空的状态 LinkStack temp = s;//定义一个存储即将被释放的空间的指针 s = s->nextPtr;// free(temp); return OK;}int pop(LinkStack &s){ int e; if (NULL == s) return ERROR; e = s->data;//存储从栈中取出的值 StackDel(s);//删除已取出的栈的空间 return e;}int push(LinkStack &s, int e){ LinkStack p = (LinkStack)calloc(1, sizeof(Stack));//动态分配空间并初始化 if (!p){ printf("Error calloc_push"); return ERROR; } p->data = e; p->nextPtr = s;//将新数据链接到链表头部 s = p; return OK;}void transform(LinkStack &s){ int e, temp = 0, pow = 1; while (NULL != s){//直到栈空 e = pop(s); temp += e*pow;//进行二进制转十进制的计算 pow *= 2;//进行位权的累乘 } printf("The octonary answer is:("); printf("%o", temp);//输出八进制结果 printf(")8\n");}void input(LinkStack &s){ char ch; printf("Please input the binary string:"); while (scanf("%c", &ch) && ch != '#'){ push(s, ch - '0');//将字符型二进制数以整型输入 } return;}int main(){ //freopen("input.txt","r",stdin); //freopen("output.txt","w",stdout); LinkStack s = NULL;//栈的头结点指针 input(s); transform(s); return 0;}