程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> 更多編程語言 >> 編程綜合問答 >> c-請大家看看這段代碼怎麼改進(我想養成好的編程習慣)。謝謝。

c-請大家看看這段代碼怎麼改進(我想養成好的編程習慣)。謝謝。

編輯:編程綜合問答
請大家看看這段代碼怎麼改進(我想養成好的編程習慣)。謝謝。

題目見圖片。
下面是代碼(這道題當然還有其他解法,我這裡是刻意用鏈表做的)
{圖片說明
#include
#include
typedef struct monkey{
int num;
struct monkey * next;
} M;
void game(int, int, int);
M create_list(M *,int );
int main(void)
{
int n;
scanf("%d", &n);
int i;
for (i = 1; i <= n; i++)
{
int n, m, p;
scanf("%d %d %d",&n, &m, &p);
game(n, m, p);
}
return 0;
}
void game(int n, int m, int p)
int j = 1;
M *headp = (M *)malloc(sizeof(M)),*tail;
tail=create_list(&headp,n);//創建大小為n的環狀鏈表,返回尾節點
M *now = headp,*before=tail;
while (now->num != p)//定位到值為p的節點
{
before = now;
now = now->next;
}
while (n - 1)//進行n-1次游戲
{
int cnt = m - 1;
while (cnt)//定位到下一個被淘汰的猴子
{
before = now;
now = now->next;
--cnt;
}
M *temp = now;
before->next = now->next;
now = now->next;
free(temp);//刪除被淘汰的猴子,定位到下一個
--n;
}
printf("%3d\n", now->num);//最後還剩一個猴子
}
M *create_list(M **head,int n)
{
M *temp = *head;
int i=1;
while (i !=n)//n個節點,依次賦值1,2....n
{
temp->num = i++;
temp->next = (M *)malloc(sizeof(M));
temp = temp->next;
}
temp->num = n;
temp->next = *head;
return temp;
}

最佳回答:


你想看什麼?編寫規范還是執行效率?

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved