采用链栈方式:
//-----------------应用举例操作-------------------//
void conversion( unsigned int Num , unsigned int x ) //进制转换:将十进制转换为X进制
{ //原理: Num = ( Num div x )* x + Num mod x ;
LinkStack S ;
ElemType e ;InitStack( &S ) ;
while( Num )
{
Push( &S , Num%x ) ;
Num = Num/x ;
}
while( !StackEmpty( S ) )
{
Pop( &S , &e ) ;
printf( "%d" , e ) ;
}
}void MachWords( char *words ) //Take care: typedef char ElemType; 括号匹配的检验
{
LinkStack S;
ElemType e;InitStack( &S ) ;
while( *words )
{
if(*words == '{'|| *words == '['|| *words == '(')
Push( &S , *words ) ;
else
{
GetTop( S , &e ) ;
if((e=='{'&&*words=='}')||(e=='['&&*words==']')||(e=='('&&*words==')'))
{
Pop( &S , &e ) ;
printf( "%c %c\n" , e , *words ) ;
}
// else { } //不合法情况
}
++words ;
}
}void LineEdit( ) //Take care: typedef char ElemType; 行编辑程序
{
LinkStack S;
ElemType e , c ;InitStack( &S ) ;
e = getchar( ) ;
while( e != EOF ) //EOF为全文结束符
{
while( e != EOF && e != '\n' )
{
switch( e )
{
case '#':Pop( &S , &c ) ; break ; //仅当栈非空时退栈
case '@':Clear( &S ) ; break ;
default :Push( &S , e ) ;break ; //有效字符
}
e = getchar( ) ;
}
StackTraverse( S , visit ) ;//将从栈底到栈顶的栈内字符传送至调用过程的数据区。此调用中即为输出数据区,也可以改写此函数,将数据区传出来!
Clear( &S ) ; //visit:char
if( e != EOF ) //EOF:ctrl+z
e = getchar( );
}
Destroy( &S ) ;
}int main( )
{
// conversion( 1348 , 8 ) ;
// print( "\n" ) ;// char words[10] = {'[','(','[',']','[',']',')',']'};
// MachWords( words ) ;LineEdit( ) ; //whli##ilr#e(s#*s) (换行) outcha@putchar(*s=#++); (ctrl+z)
return 0 ;
}
第三章(5).栈的应用举例(1)
最新推荐文章于 2022-04-02 17:00:32 发布