- 论坛徽章:
- 1
|
母牛数量算法
大家看看我的程序:
- # include <stdio.h>;
- class cow
- {
- public:
- static cow *head;
- static cow *tail;
- static unsigned long cowCount;
- int age;
- cow *next;
- cow()
- {
- age = 0;
- next = ( cow * ) NULL;
- }
- void grow(void)
- {
- age++; // 年龄长了一岁。
- if ( age >;= 4 )
- { // 第四个年头起,下崽。
- cow *child = new cow;
- tail->;next = child;
- tail = child;
- cowCount++;
- }
- }
- };
- unsigned long cow::cowCount = 0;
- cow *cow::head = NULL;
- cow *cow::tail = NULL;
- int main( void )
- {
- int years = 30;
- cow *cows = new cow;
- cow::head = cows;
- cow::tail = cows;
- cow::cowCount = 1;
- for( int i=0; i<years; i++ )
- for( cow *ptr = cow::head; ptr != NULL; ptr = ptr->;next ) // 一年过去了,每牛(注意:不能叫“每人”)给我长一岁。
- ptr->;grow();
- printf( "result: [%ld]\n", cow::cowCount );
- ptr = cow::head;
- while( ptr != NULL )
- {
- cow *temp = ptr;
- ptr = ptr->;next;
- delete temp;
- }
- return 1;
- }
复制代码 |
|