資料結構用順序棧實現R進位制轉換
阿新 • • 發佈:2018-12-20
#include<stdio.h> #define MAXSIZE 500 typedef struct{ int *base; int *top; int stacksize; }Sqstack; int Initstack(Sqstack &S){//順序棧的初始化 S.base=new int[MAXSIZE]; S.top=S.base; S.stacksize=MAXSIZE; return 1; } int Push(Sqstack &S,int e){//入棧 if(S.top-S.base==S.stacksize) return -1;//-1時棧滿 *S.top++=e; return 1; } int Pop(Sqstack &S,int e){//出棧 if(S.top==S.base ) return -1;//-1時棧空 e=*--S.top ; return e; } int Gettop(Sqstack S){//只取棧頂元素,不改變棧 if(S.base!=S.top ) return *(S.top-1); } int main(){ int n,r; printf("輸入N和R\n"); Sqstack S;//定義棧 while(scanf("%d%d",&n,&r)!=EOF){ Initstack(S);//棧的初始化 int a,mod; while(n){ mod=n%r; n=n/r; if(Push(S,mod)) printf("入棧成功\n"); else printf("入棧失敗\n"); } while(S.top!=S.base ){ int e; a=Pop(S,e); if(a==-1) printf("佔空") ; else if(a<11) printf("%d ",a); else printf("%c",11+54) ; } printf("輸入N和R\n"); } }