利用棧實現進制轉換
#include<malloc.h>
#define MAX_STACK_SIZE 10//靜態棧向量大小
#define ERROR 0
#define OK 1
typedef int ElemType;
typedef int Status;
/
棧的應用:
進制轉換
/
typedef struct sqstack{
ElemType stack_array[MAX_STACK_SIZE];
// int size;
int top;
int bottom;
}SqStack;
//初始化棧
void Init_Stack(SqStack *S){
S->bottom=S->top=0;
}
//壓棧(元素進棧)
Status push(SqStack *S , ElemType e){
if(S->top >= MAX_STACK_SIZE - 1){
printf("棧滿!\n");
return ERROR;//棧滿
}
printf("--------");
printf("當前入棧元素:%d\n",e);
// printf("入棧前S->top==%d\n",S->top);
S->top++;//位置自加
// S->size++;
printf("入棧後S->top==%d\n",S->top);
S->stack_array[S->top] = e;//元素入棧
return OK;
}
//彈棧(元素出棧)
Status pop(SqStack *S , ElemType e){
if(S->top == 0){
return ERROR;//棧空
}
e = S->stack_array[S->top];//先取
printf("當前應當出棧:%d\n",e);
S->top--;//自減
// printf("size==%d",S->size);
return OK;
}
//遍歷棧
Status StackTravel(SqStack *S){
int e;
int ptr;
ptr = S->top;
while(ptr > S->bottom){
e = S->stack_array[ptr];
ptr--;
printf("%d",e);
}
}
void conversion(int n , int d){
SqStack S;//創建棧
ElemType k;//欲進棧的元素
int temp = n;//保存n
Init_Stack(&S);//初始化棧
// printf("--入棧初始:S->top==%d\n",S.top);
while(n>0){
k = n % d;//取余
push(&S,k);//余數進棧
n = n / d;//結果取整
}
printf("將%d轉化成%d進制後為:",temp,d);
StackTravel(&S);//遍歷棧
}
int main(){
conversion(511, 2);
conversion(512, 2);
}
利用棧實現進制轉換