随便写了个. 但求容易阅读...
- #include <stdio.h>
- #include <stdlib.h>
- struct LoopLink
- {
- int id;
- struct LoopLink *next;
- };
- int loopNum = 0;
- struct LoopLink *Create( int num )
- {
- struct LoopLink *ret = NULL; //这里ret其实就是将要返回的"头"节点, 但环形的东西叫"头"总是很别扭的.
- if ( num > 0 )
- {
- int i;
-
- ret = ( struct LoopLink * ) malloc( sizeof( struct LoopLink ) );
- ret->id = 1;
- ret->next = NULL;
- struct LoopLink *p = ret;
- for ( i = 1;i < num;i++ )
- {
- p->next = ( struct LoopLink * ) malloc( sizeof( struct LoopLink ) );
- p->next->id = i + 1;
- p->next->next = NULL;
- p = p->next;
- }
- p->next = ret; //串起来, 最后一个节点指向"头"节点.
- }
- loopNum = num;
- return ret;
- }
- void PrintLoop( struct LoopLink *p )
- {
- int i;
- for ( i = 0;i < loopNum;i++ )
- {
- printf( "%4d", p->id );
- p = p->next;
- }
- printf( "/n" );
- }
- void KickOutTheOneAfter( struct LoopLink *p )
- {
- struct LoopLink *thePoorOne = p->next;
- p->next = thePoorOne->next;
- free( thePoorOne );
- loopNum--;
- }
- struct LoopLink *StartGame( struct LoopLink *p, int interval )
- {
- while ( loopNum > 1 )
- {
- int i;
- //bug when interval == 1
- for ( i = 1;i < interval - 1 ;i++ )
- {
- p = p->next;
- }
- KickOutTheOneAfter( p );
- p = p->next;
- PrintLoop( p );
- }
- return p;
- //returning the last one.
- }
- int main( void )
- {
- struct LoopLink *myLoop = Create( 13 );
- PrintLoop( myLoop );
- struct LoopLink *theLastOne;
- theLastOne = StartGame( myLoop, 3 );
- free(theLastOne);
- return 0;
- }