数据结构:数制转换

时间:2025-03-13 21:18:27

十进制数 N 和其他 d 进制数 转换原理:
N= (N div d ) x d + N mod d(div为整除运算 mod为求余运算)

对于输入的任意的一个非负十进制整数,打印输出与其值的八进制数。由于上诉计算过程是从低到高位顺序产生八进制的各个数位,而打印输出,一般来说应从高位到低位进行,恰好和计算过程相反。因此,若将计算过程得到的八进制数的各位顺序进栈,则按出栈序列打印输出的即为与输入对应的八进制数。

#include<>
#include<>


    typedef struct Node{
        int Data;
        struct Node *Next;
    } LinkStack ;   

    LinkStack *CreateStack(){
        LinkStack *S;
        S = (LinkStack *)malloc(sizeof(LinkStack));
        S->Next = NULL;
        return S;
    }

    int isEmpty(LinkStack *S){
        return (S->Next == NULL) ;  //若为空 返回1
    }

    LinkStack *Push(LinkStack *S,int item){
        LinkStack *TempCell;
        TempCell = (LinkStack *)malloc(sizeof(LinkStack));
        TempCell->Data = item;
        TempCell->Next = S->Next;
        S->Next = TempCell;
        //  free(TempCell);
        /* 
        一开始在这里出错了 这里的不能把调用free(TempCell)
        */

    }

    int Pop(LinkStack *S){
        LinkStack *FirstCell;
        int TopElem;
        if(isEmpty(S)){
            printf("堆栈空\n");
            return 0 ;
        }else{
            FirstCell  = S->Next;
            S->Next = FirstCell->Next;
            TopElem = FirstCell->Data;
           free(FirstCell);
            return TopElem;
        }
    }

    void conversion(){
        LinkStack *s;
        int n;
        int item;

         s = CreateStack();

        scanf("%d",&n);

        while(n){
            Push(s,n%8);
            n = n/8;
        }
        while(!isEmpty(s)){
            int item;
            item = Pop(s);
            printf("%d", item);
        }
        printf("\n");

}

    int main(){

            conversion();

        return 0;
    }