棧的應用:十進位轉八進位

來源:互聯網
上載者:User

PS:資料結構 48頁棧的應用

十進位轉換八進位

自己寫了下。供大家參考,通過源碼進一步學習資料結構。

 

此書全部給出演算法思想

要自己多動手敲敲code,不能光看不敲,那是沒用的,給你思路,你也照樣寫不出來

要做一個合格的程式員就努力的寫代碼。通過代碼量反映你的能力

 

 

//利用棧實現進位間的轉換
#include<stdio.h>
#include<stdlib.h>
//#include<malloc.h>
#include<conio.h>
#define STACK_INIT_SIZE   100
#define STACKINCREMENT    10
typedef struct{
    int *base;
    int *top;
    int stacksize;
}SqStack;
int InitStack(SqStack &S)//構造空棧
{
    S.base = (int *)malloc(sizeof(int) * (STACK_INIT_SIZE));
    if(!S.base) exit(-1);
    S.top = S.base;
    S.stacksize = STACK_INIT_SIZE;
    return 1;
}
int Push(SqStack &S, int e)//壓棧
{
    if(S.top - S.base >= S.stacksize)
    {
    S.base = (int *)realloc(S.base, sizeof(int) * (STACK_INIT_SIZE + STACKINCREMENT));
    if(!S.base) exit(-1);
    S.top = S.base + S.stacksize;
    S.stacksize += STACKINCREMENT;
    }
    *S.top++ = e;
    return 1;
}
int  StackEmpty(SqStack S)//查看棧是否為空白
{
    if(S.base == S.top) return 1;
    else return 0;
}
int  Pop(SqStack &S, int &e)//出棧
{
    if(S.top == S.base) return 0;
    e = *--S.top; 
    return 1;
}
void conversion()//將十進位用棧轉化為八進位
{
    SqStack S;
    int N;
    int e;
    InitStack(S);
    printf("輸入N的值:");
    scanf("%d",&N);
    printf(" 轉換後的值:");
    while(N)
    {
        Push(S, N % 8);
        N = N/8;
    }
    while(!StackEmpty(S))
    {
        Pop(S,e);
        printf(" %d",e);
    }
}
void main()
{
    conversion();
    getch();
}

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.