- #include <stdio.h>
- #include <malloc.h>
- #include <stdlib.h>
- #define OK 0
- #define ERROR 1
- #define STOCKINT 100
- #define STOCKINCREASE 10
- //-----------------------------------------------
- typedef int Status;
- typedef int SElemType;
- typedef int ElemType;
- typedef struct
- {
- SElemType * base;
- SElemType * top;
- int stocksize;
- }SqStack;
- //-------------------------------create function
- Status createstock( SqStack &S ); //create stock
- Status pushstock( SqStack &S, int mode ); // push
- Status popstock( SqStack &S, int &div ); // pop
- Status destorystock( SqStack &S ); // destory
- Status stockempty( SqStack &S ); // is empty?
- void convert( SqStack &S );
- int num( SqStack S );
- int main()
- {
- SqStack S;
- if( createstock( S ) == OK )
- printf( "create success\\n" );
- else
- exit( 0 );
- convert( S );
- return 0;
- }
- Status createstock( SqStack &S )
- {
- S.base = ( SElemType * )malloc( sizeof(SElemType) * STOCKINT );
- S.top = S.base;
- S.stocksize = STOCKINT;
- if( S.base )
- return OK;
- else
- return ERROR;
- }
- void convert( SqStack &S )
- {
- int num, e;
- puts( "now you are entering the function" );
- printf( "please tell me a number (10 to 2):" );
- scanf( "%d", &num );
- while( num )
- {
- pushstock( S, num % 8);
- num /= 8;
- // printf( "%d", num( S ) );
- }
- printf( "after convert:");
- while( stockempty( S ) )
- {
- popstock( S, e);
- printf( "%d", e );
- }
- }
- Status pushstock( SqStack &S, int mode ) //push
- {
- if( S.top - S.base >= S.stocksize )
- {
- S.base = ( SElemType * )realloc( S.base,
- sizeof(SElemType) * (STOCKINCREASE + S.stocksize) );
- if( !S.base )
- exit( 0 );
- S.top = S.base + S.stocksize;
- S.stocksize += STOCKINCREASE;
- }
- *(S.top) = mode;
- S.top ++;
- return OK;
- }
- Status popstock( SqStack &S, int &div )
- {
- if( S.top == S.base )
- return ERROR; //empty stack!!
- div = * --S.top ;
- }
- Status destorystock( SqStack &S )
- {
- free( S.base );
- free( S.top );
- S.stocksize = 0;
- return OK;
- }
- Status stockempty( SqStack &S )
- {
- if( S.top == S.base)
- return OK;
- else
- return ERROR;
- }
- int num( SqStack S )
- {
- return ( S.top - S.base );
- }
- //该片段来自于http://www.codesnippet.cn/detail/220120131842.html
来源: http://www.codesnippet.cn/detail/220120131842.html