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();
}