第一题:使用循环链表实现约瑟夫环
主要函数
尾插函数
int list_insert_tail ( Looplink* L, datatype e)
{
if ( NULL == L)
{
printf ( "所给链表不合法\n" ) ;
return - 1 ;
}
Looplink* p = ( Looplink* ) malloc ( sizeof ( Looplink) ) ;
if ( NULL == p)
{
printf ( "节点申请失败!\n" ) ;
return - 2 ;
}
p-> data= e;
p-> next = NULL ;
Looplink* q = L;
while ( q-> next != L)
{
q = q-> next;
}
p-> next = L;
q-> next = p;
L-> len++ ;
return 0 ;
}
删除头结点函数
Looplink* delete_head ( Looplink* L)
{
if ( NULL == L|| list_empty ( L) )
{
printf ( "删除失败\n" ) ;
return NULL ;
}
Looplink* p = L-> next;
while ( p-> next!= L)
{
p = p-> next;
}
p-> next = L-> next;
free ( L) ;
L= NULL ;
return p-> next;
}
约瑟夫环函数
void Circle ( Looplink* L, int n, int m)
{
Looplink* q = L;
while ( n> 0 )
{
for ( int i= 1 ; i< m- 1 ; i++ )
{
q= q-> next;
}
Looplink* p = q-> next;
q-> next = p-> next;
printf ( "%d\t" , p-> data) ;
free ( p) ;
p= NULL ;
q= q-> next;
n-- ;
}
printf ( "\n" ) ;
}
主函数测试
int main ( int argc, const char * argv[ ] )
{
Looplink* L = list_create ( ) ;
if ( NULL == L)
{
return - 1 ;
}
int m, n;
printf ( "请输入n>>>" ) ;
scanf ( "%d" , & n) ;
printf ( "请输入m>>>" ) ;
scanf ( "%d" , & m) ;
for ( int i= 0 ; i< n; i++ )
{
list_insert_tail ( L, i+ 1 ) ;
}
Looplink* S = delete_head ( L) ;
L = NULL ;
Circle ( S, n, m) ;
return 0 ;
}
测试结果
第二题:使用栈的特点完成进制转换
主要函数
入栈函数
int push ( seqStack* S, datatype e)
{
if ( NULL == S|| full ( S) )
{
printf ( "入栈失败!\n" ) ;
return - 1 ;
}
S-> data[ ++ S-> top] = e;
return 0 ;
}
进制转换函数
void JZZH ( seqStack* S)
{
int n, m;
printf ( "请输入待转换的十进制数>>>" ) ;
scanf ( "%d" , & n) ;
printf ( "请输入进制>>>" ) ;
scanf ( "%d" , & m) ;
while ( n/ m!= 0 )
{
push ( S, n% m) ;
n/= m;
}
push ( S, n% m) ;
show ( S) ;
}
从栈顶到站底遍历函数
void show ( seqStack* S)
{
if ( NULL == S|| empty ( S) )
{
printf ( "遍历失败!\n" ) ;
return ;
}
printf ( "转换后为:" ) ;
for ( int i= S-> top; i>= 0 ; i-- )
{
if ( S-> data[ i] == 10 )
printf ( "A" ) ;
else if ( S-> data[ i] == 11 )
printf ( "B" ) ;
else if ( S-> data[ i] == 12 )
printf ( "C" ) ;
else if ( S-> data[ i] == 13 )
printf ( "D" ) ;
else if ( S-> data[ i] == 14 )
printf ( "E" ) ;
else if ( S-> data[ i] == 15 )
printf ( "F" ) ;
else
printf ( "%d" , S-> data[ i] ) ;
}
printf ( "\n" ) ;
}
主函数测试
int main ( int argc, const char * argv[ ] )
{
seqStack * S = create ( ) ;
if ( NULL == S)
{
return - 1 ;
}
JZZH ( S) ;
destroy ( S) ;
S= NULL ;
return 0 ;
}
测试结果