学.....佛......有恒
函数: #include <stdio.h> #include <stdlib.h> #include "MyHeadFile.H"
struct Monkey *CreateList( int MonkeyNumber ) //根据用户输入的猴子数生成循环链表。较数组的优点在于从理论上可以不确定猴子数量的多少(只要你内存够大,CPU够彪悍) { struct Monkey *head = NULL; struct Monkey *tail = NULL; struct Monkey *temp = NULL;
for ( int i = 0; i < MonkeyNumber; i++ ) { temp = ( struct Monkey *)malloc(sizeof(struct Monkey)); if ( temp == NULL ) { printf("Out Of Memory!\n"); return head; } temp->pNext = head;
if ( head == NULL ) { head = tail = temp; head->MonkeyID = 1; } else { tail->pNext = temp; tail = temp; tail->MonkeyID = i + 1; } } return head; }
void ViewList( struct Monkey *head ) { struct Monkey *p = head;
do { printf("ID:%d\n",p->MonkeyID); p = p->pNext ; } while ( p != head ); }
//释放内存 void FreeList( struct Monkey *head ) //定义*PTEMP作为保留下一节点指针的变量 { struct Monkey *p = head; struct Monkey *ptemp = p;
do { ptemp = p->pNext; free(p); p = ptemp; } while (p != head); } //删除链表单元 struct Monkey *DeleteMonkey( struct Monkey **head, int MonkeyNumber ) //第一个参数为指针的指针,为了改变主函数中的HEAD值 { struct Monkey *pDel = NULL; //删除目标 struct Monkey *pTEMP = NULL; //用做保存上一节点的临时变量 struct Monkey *pFREE = NULL; //用做保存用于释放的地址节点的临时变量 int i;
if ( MonkeyNumber == 1 ) //输入报数为一的时候猴子为最后一只 { pDel = *head; do { pTEMP = pDel->pNext; free(pDel); pDel = pTEMP; } while (pDel->pNext != *head); pDel->pNext = *head = pDel; //完成循环链表 return *head; } while ( (*head)->pNext != *head ) //循环删除节点直到仅盛下一个单元即(*head)->pNext != *head { pDel = *head; for ( i = 0; i < MonkeyNumber - 1; i ++ ) { pTEMP = pDel; pDel = pDel->pNext; //向后数猴子 } pFREE = pDel; pTEMP->pNext = pDel->pNext; *head = pDel->pNext ; //重新定位头,准备开始重新报数 free(pFREE); pFREE = NULL; }
return *head; }
[此贴子已经被作者于2005-10-27 0:46:11编辑过]
Main函数 /*猴子选大王之循环链表版*/ #include <stdio.h> #include <stdlib.h> #include "MyHeadFile.H"
void main(void) { int MonkeyNumber = 0; int CountNumber = 0; struct Monkey *pMonkey = NULL;
printf("Input Monkey Number:"); //输入猴子数量 scanf("%d",&MonkeyNumber);
printf("Input Count Number:"); //输入报数周期 scanf("%d",&CountNumber);
pMonkey = CreateList( MonkeyNumber ); //建立循环链表 // ViewList( pMonkey );
pMonkey = DeleteMonkey( &pMonkey, CountNumber );
ViewList( pMonkey ); FreeList( pMonkey );
}
[此贴子已经被作者于2005-10-27 0:41:24编辑过]
头文件:"MyHeadFile.H" #ifndef INCLUDE_MYHEADFILE_H #define INCLUDE_MYHEADFILE_H
struct Monkey //定义结构体 { int MonkeyID; struct Monkey *pNext; };
//函数声明
struct Monkey *CreateList( int MonkeyNumber ); void FreeList( struct Monkey *head ); void ViewList( struct Monkey *head ); struct Monkey *DeleteMonkey( struct Monkey **head, int MonkeyNumber );
#endif
程序如下,最简单了,只要输入猴子数量,就能立刻告诉你结果! #include <stdio.h> void main() {
int j=1,n;
printf("Please input monkeys's number:\n"); scanf("%d",&n); loop: j=j*2; if(j<=n) goto loop; j=j/2; printf("last speak '1' 's monkey is No.%d",j); }