題目見圖片。
下面是代碼(這道題當然還有其他解法,我這裡是刻意用鏈表做的)
{
#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;
}
你想看什麼?編寫規范還是執行效率?