第6周 项目4- 数制转换.

来源:互联网 发布:linux笔记 编辑:程序博客网 时间:2024/04/30 22:49
/* *文件名称:1.pp *作者:崔从敏 *完成日期:2015年10月9日 *问题描述:数制转换.*/#include <stdio.h>#include <malloc.h>typedef int ElemType;typedef struct linknode{    ElemType data;              //数据域    struct linknode *next;      //指针域} LiStack;                      //链栈类型定义void InitStack(LiStack *&s);  //初始化栈void DestroyStack(LiStack *&s);  //销毁栈int StackLength(LiStack *s);  //返回栈长度bool StackEmpty(LiStack *s);  //判断栈是否为空void Push(LiStack *&s,ElemType e);  //入栈bool Pop(LiStack *&s,ElemType &e);  //出栈bool GetTop(LiStack *s,ElemType &e);  //取栈顶元素void DispStack(LiStack *s);  //输出栈中元素void MultiBaseOutput (int number,int base);void InitStack(LiStack *&s)  //初始化栈{    s=(LiStack *)malloc(sizeof(LiStack));    s->next=NULL;}void DestroyStack(LiStack *&s)  //销毁栈{    LiStack *p=s->next;    while (p!=NULL)    {        free(s);        s=p;        p=p->next;    }    free(s);    //s指向尾结点,释放其空间}int StackLength(LiStack *s)  //返回栈长度{    int i=0;    LiStack *p;    p=s->next;    while (p!=NULL)    {        i++;        p=p->next;    }    return(i);}bool StackEmpty(LiStack *s)  //判断栈是否为空{    return(s->next==NULL);}void Push(LiStack *&s,ElemType e)  //入栈{    LiStack *p;    p=(LiStack *)malloc(sizeof(LiStack));    p->data=e;              //新建元素e对应的节点*p    p->next=s->next;        //插入*p节点作为开始节点    s->next=p;}bool Pop(LiStack *&s,ElemType &e)  //出栈{    LiStack *p;    if (s->next==NULL)      //栈空的情况        return false;    p=s->next;              //p指向开始节点    e=p->data;    s->next=p->next;        //删除*p节点    free(p);                //释放*p节点    return true;}bool GetTop(LiStack *s,ElemType &e)  //取栈顶元素{    if (s->next==NULL)      //栈空的情况        return false;    e=s->next->data;    return true;}void DispStack(LiStack *s)  //输出栈中元素{    LiStack *p=s->next;    while (p!=NULL)    {        printf("%c ",p->data);        p=p->next;    }    printf("\n");}void MultiBaseOutput (int number,int base){    //假设number是非负的十进制整数,输出等值的base进制数    int i;    LiStack *S;    InitStack(S);    while(number)   //从右向左产生base进制的各位数字,并将其进栈    {        Push(S,number%base); //将将余数进栈        number/=base;    }    while(!StackEmpty(S))   //栈非空时退栈输出    {        Pop(S, i);        printf("%d",i);    }}int main(){    MultiBaseOutput(10, 2);    return 0;}


运行结果:

0 0