棧的應用 十進制與八進制的轉換

#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 返回的指針值是否相同。

參考這裏: http://blog.csdn.net/snlying/article/details/4005238

還有這裏:   http://www.cplusplus.com/reference/cstdlib/realloc/

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章