Мой код состоит в том, чтобы реализовать игру с «горячим картофелем», используя круговой связанный список, в котором пользователь выбирает количество игроков и количество проходов.Например, если пользователь выбирает 3 игрока и 2 паса, начиная с игрока 1, первым должен быть удален игрок 3. Играйте снова на следующем игроке, игрок 1 будет удален, что сделает игрока 2 победителем.Моя программа работает хорошо с некоторыми условиями, но, например, если я выберу 8 игроков и 3 прохода, я увижу «Игрок 0 был удален», и 0 никогда не должно быть в списке.Как добавляется 0?Вот мой кодФункция отображения была только для целей отладки, не нужна.
#include <iostream>
using namespace std;
struct node
{
int data;
node *next;
};
class List
{
private:
node * head;
node * tail;
int size;
public:
List()
{
head = NULL;
tail = NULL;
size = 0;
}
void add_node(int value);
void display();
void delete_node(int value);
int Size()
{
return size;
}
node * Head()
{
return head;
}
};
void createPlayers(List& myList, int N);
void playGame(List& myList, int X);
int main()
{
List myList;
int N;
int X;
cout << "Welcome to the Hot Potato game" << endl;
cout << "Please enter the number of people" << endl;
cin >> N;
cout << "Please enter the number of passes" << endl;
cin >> X;
createPlayers(myList, N);
myList.display();
playGame(myList, X);
myList.display();
return 0;
}
void List::add_node(int value)
{
node *temp = new node;
temp->data = value;
temp->next = head;
if (head == NULL)
//
{
head = temp;
tail = temp;
temp = NULL;
}
else
{
tail->next = temp;
tail = temp;
}
size++;
}
void List::display()
{
node *temp = new node;
cout << "Nodes in queue: ";
temp = head;
cout << temp->data << ",\t";
temp = head->next;
while (temp != head)
{
cout << temp->data << ",\t";
temp = temp->next;
}
cout << "\n";
}
void List::delete_node(int value)
{
node*tempPrev = head;
node*temp = head;
while (temp->data != value)
{
tempPrev = temp;
temp = temp->next;
}
if (temp == head)
{
head = head->next;
tail->next = head;
}
else
{
tempPrev->next = temp->next;
}
delete temp;
size--;
}
void createPlayers(List& myList, int N)
{
for (int i = 1; i <= N; i++)
{
myList.add_node(i);
}
}
void playGame(List& myList, int X)
{
node * start = myList.Head();
while (myList.Size() != 1)
{
int i = 0;
while (i < X)
{
start = start->next;
i++;
}
cout << "Player " << start->data << " has been eliminated" << endl;
myList.display();
myList.delete_node(start->data);
myList.display();
start = start->next;
if (myList.Size() == 1)
{
cout << "Player " << start->data << " is the winner" << endl;
//break;
}
}
}