用栈实现十进制转换为八进制
首先,建立两个自定义的.h文件 conn.h 和stack.hconn.hstack.h:#ifndef conn_h_
#define conn_h_
#define TRUE 1
#define FALSE 0
#define OK 1
#define ERROR 0
#define INFEASIBLE -1
#define OVERFLOW -2
typedef int status;
#endif
stack.h中的内容:#ifndef _stack_h_
#define _stack_h_
#define stack_init_size 100
#define stackincrement 10
typedef int selemtype;
typedef int status;
typedef struct{
selemtype *base;
selemtype *top;
int stacksize;
}sqstack;
status initstack(sqstack &s);
status push(sqstack &s,selemtype e);
status pop(sqstack &s,selemtype &e);
status stackempty(sqstack s);
#endif
在建立两个.cpp文件 stack.cpp和test.cpp
stack.h中的内容:
#include "stdafx.h"
#include "stdlib.h"
#include "conn.h"
#include "stack.h"
status initstack(sqstack &s){
s.base=(selemtype *)malloc(stack_init_size *sizeof(selemtype));
if (!s.base) exit(OVERFLOW);
s.top=s.base;
s.stacksize=stack_init_size;
return OK;
}
status gettop(sqstack s,selemtype &e){
if (s.top==s.base) return ERROR;
e=*(s.top-1);
return OK;
}
status stackempty(sqstack s){
return s.base==s.top;
}
status push(sqstack &s,selemtype e){
if(s.top-s.top>=s.stacksize){
s.base=(selemtype *)realloc(s.base,(s.stacksize+stackincrement)*sizeof(selemtype));
if(!s.base)exit(OVERFLOW);
s.top=s.base+s.stacksize;
s.stacksize+=stackincrement;
}
*s.top++=e;
return OK;
}
status pop(sqstack &s,selemtype &e){
if(s.top==s.base)return ERROR;
e=*--s.top;
return OK;
}
test.cpp中的内容为:
// test.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "stdio.h"
#include "stack.h"
#include "conn.h"
void conversion(){
int n;
int e;
sqstack s;
initstack (s);
printf("请输入十进制的数");
scanf("%d",&n);
while(n){
push(s,n%8);
n=n/8;
}
printf("对应的八进制数为\n");
while(!stackempty(s)){
pop(s,e);
printf("%d",e);
}
}
int main(int argc, char* argv[])
{
conversion();
return 0;
}
即可快速实现!