I am writing a program that creates a linked list of 5 players and would like to sort them by their scores (total). My main program works fine, that is the linked list is created successfully. However i am having some trouble with the sorting function. It swaps the first two nodes correctly, but then it seems to be stuck in an infinite loop. Any help and tips are appreciated
#include<iostream>
#include<string>
usingnamespace std;
class player //defining member function
{
public: //declaring variables within the structure
int match;
int score; //array used since the score for each match is stored
int agg(int);
int total;
int num;
class player *next;
};
//declaring global variable
int sum;
player *node;
int agg(int aggregate) //function to find the aggregate score of each batsmen
{
sum = sum + aggregate;
return sum;
}
void sort();
//main function
int main()
{
//declaring variables
int l=0, m=0; int k=0; int i=0, j=0; int n=1;
player batsman1, batsman2, batsman3, batsman4, batsman5; //declaring 5 variables of type player (struct)
node = &batsman1;//creating node pointer to point to first 'batsman'
//requesting user input for data for first batsman
batsman1.num =1;
batsman1.match = 1;
batsman1.score= 24;
batsman1.total = agg(batsman1.score);//calls on agg function to calculate and store total runs for the batsman
batsman1.next = &batsman2; //creates link between node 1 and 2 of the list
//requesting user input for data for second batsman
batsman2.num =2;
batsman2.match =1;
sum=0;
batsman2.score = 34;
batsman2.total = agg(batsman2.score); //calls on agg function to calculate and store total runs for the batsman
batsman2.next = &batsman3;//creates link between node 2 and 3 of the list
//requesting user input for data for third batsman
batsman3.num =3;
batsman3.match=1;
sum=0;
batsman3.score=100;
batsman3.total = agg(batsman3.score);//calls on agg function to calculate and store total runs for the batsman
batsman3.next = &batsman4;//creates link between node 3 and 4 of the list
//requesting user input for data for fourth batsman
batsman4.num =4;
batsman4.match=1;
sum=0;
batsman4.score= 12;
batsman4.total = agg(batsman4.score);//calls on agg function to calculate and store total runs for the batsman
batsman4.next = &batsman5;//creates link between node 4 and 5 of the list
//requesting user input for data for fifth batsman
batsman5.num =5;
batsman5.match=1;
sum=0;
batsman5.score= 2;
batsman5.total = agg(batsman5.score);//calls on agg function to calculate and store total runs for the batsman
batsman5.next = 0; //links last node of list to null
sort();
while(node != 0)
{
cout<<"Batsman "<<node->num<<" Aggregate: "<<node->total<<endl;
node = node->next;
system("PAUSE");
}
return 0;
}
void sort ()
{
player* temp; int p=1, p2=0;
temp = NULL;
for (p=1; p<6; p++)
{
for(p2=0; p2<6-p;p2++)
{
if ((node->next)->total > node->total)
{
temp = node;
node = node->next;
node->next = temp;
}
node = node->next;
}
}
}