30位同學圍成一圈,由第一位開始報1~n,每報到n時舉手,在輪過幾輪(Cycle)後,才會開始有人重覆舉手?
請用以程式用Linked List的寫法印出以下結果。
n=1 Cycle: 30
n=2 Cycle: 15
n=3 Cycle: 10
n=4 Cycle: 15
n=5 Cycle: 6
n=6 Cycle: 5
n=7 Cycle: 30
n=8 Cycle: 15
n=9 Cycle: 10
n=10 Cycle: 3
下面的程式碼只能列出每一組前30位的舉手者是誰,不知要如何更改才能得到以上的結果...
#include <iostream>
#include <stdlib.h>
using namespace std;
struct node* ptr;
struct node* head;
struct node* tail;
struct node{
int num;
struct node* next;
};
void AddNodeFromTail(int C)
{
ptr = (struct node*) malloc( sizeof(node)) ;
ptr->num = C;
tail->next = ptr;
ptr->next = NULL;
tail = ptr;
}
void AddFirstNode(int C)
{
ptr = (struct node*) malloc( sizeof(node)) ;
head = ptr;
ptr->num = C;
tail = ptr;
ptr->next = NULL;
}
void FindNextNode(int n)
{
for(int i=0;i<n;i++)
{
ptr=ptr->next;
}
cout << ptr->num << " ";
}
int main(){
AddFirstNode(1);
for (int i=2; i<=30; i++)
{
AddNodeFromTail(i);
}
for (int x=1; x<=10; x++)
{
cout << "n=" << x << "\n";
tail->next = head;
ptr=head;
FindNextNode(x-1);
for (int i=0;i<29;i++)
FindNextNode(x);
cout << "\n";
}
}
#include <iostream>
#include <stdlib.h>
using namespace std;
struct node* ptr;
struct node* head;
struct node* tail;
struct node{
int num;
struct node* next;
};
void AddNodeFromTail(int C)
{
ptr = (struct node*) malloc( sizeof(node)) ;
ptr->num = C;
tail->next = ptr;
ptr->next = NULL;
tail = ptr;
}
void AddFirstNode(int C)
{
ptr = (struct node*) malloc( sizeof(node)) ;
head = ptr;
ptr->num = C;
tail = ptr;
ptr->next = NULL;
}
void FindNextNode(int n)
{
for(int i=0;i<n;i++)
{
ptr=ptr->next;
}
//cout << ptr->num << " ";
}
int main(){
AddFirstNode(1);
for (int i=2; i<=30; i++)
{
AddNodeFromTail(i);
}
tail->next = head;
for (int n=1;n<=10;n++) {
int Cycle = 1;
ptr=head;
while (Cycle < 100) {
FindNextNode(n);
if (ptr->num==1) {
break;
}
Cycle = Cycle + 1;
}
cout << "n=" << n << " Cycle:" << Cycle << endl;
}
}
我可以直接算...
最大公因數嗎?
但是我怎麼覺得...
這個結果怪怪的...