#include <iostream>
using namespace std;
#define STACK_INIT_SIZE 100
#define STACK_INCREATEMENT 10
typedef struct node {
int *base;
int *top;
int size;
}sqStack;
/*
* 初始化对战
*
* @return 0
*
* @param s 传入的堆栈
*/
int initStack(sqStack &s)
{
s.base = ( int * )malloc( STACK_INIT_SIZE * sizeof( int ) );
if( !s.base )exit(-1);
s.top = s.base;
s.size = STACK_INIT_SIZE;
return 0;
}
/*
* 这里返回值为一个int 传入一个地址取值 这样做的好处是
* 返回值有返回值的作用 取值有取值的作用 可以根据返回值对方法的执行做判断
*
*
*/
int getTop( sqStack &s, int &elem )
{
if( s.base == s.top )
return 0;
elem = *(s.top - 1);
return 1;
}
int push(sqStack &s, int elem)
{
if( s.top - s.base == s.size ){
s.base = ( int * )realloc( s.base, ( s.size + STACK_INCREATEMENT ) * sizeof( int ) );
if( !s.size ) exit(-1);
s.top = s.base + s.size;
s.size += STACK_INCREATEMENT;
}
*s.top++ = elem;
return 1;
}
int pop(sqStack &s, int &elem)
{
if( s.top == s.base ) return -1;
elem = * --s.top;
return 1;
}
int stackEmpty(sqStack &s)
{
return s.top == s.base;
}
int main()
{
int choice;
long n= 0;
sqStack s;
initStack( s );
select:
while( !stackEmpty( s ) ){
pop( s, choice);
}
choice = 0;
cout<<"------------------------------------------------------------------------------"<<endl;
cout<<" choice1 : Decimal To Octal "<<endl;
cout<<" choice2 : Octal To Decimal "<<endl;
cout<<"------------------------------------------------------------------------------"<<endl;
cout<<"Please Enter YOUR CHOICE: \t";
cin>>choice;
if( 1 == choice ){
cout<<"Enter num:";
cin>>n;
while( n ){
push(s, n % 8 );
n = n / 8;
}
int e = 0;
while( !stackEmpty( s ) ){
pop( s, e);
cout<<e<<'\t';
}
cout<<endl;
goto select;
}else if( 2 == choice ) {
cout<<"Enter num:";
cin>>n;
while( n ){
push( s, n % 10 );
n = n / 10;
}
long ret = 0;
int e = 0;
while( !stackEmpty( s ) ){
pop( s, e );
ret = ret*8 + e;
}
cout<<"ret = "<<ret<<endl;
goto select;
} else if ( 0 == choice ){
} else {
cout<<"No such Choice ! if You wana quit, Enter 0. Enter Again..."<<endl;
goto select;
}
return 0;
}
堆栈的一个应用。 十进制与八进制的转换
注意realloc 的使用,realloc 是 在指针指向的现有内存的基础上,在现有内存后面 申请一段附加内存,如果空间足够 realloc 不会发生数据移动,直接申请新的内存空间,否则查找新的 一块内存,并把原有的数据拷贝过去,此时 原有的指针指向的 内存 就可能被 回收到 堆 了。 所以在realloc 后面要判断 新指针与realloc 返回的指针值是否相同。