I need "HELP"(do not use help for topic but not content) HAHAHAHAA!!!! LOL!!!
Seriously, this code compiles but it duplicates content of the first node with that of the second, can one help? I am actually trying to sort the nodes from youngest to oldest.
//aim: sorting nodes
//----------------------header files---------------------------------------------
#include <iostream>
#include <cstdlib>
//----------------------namespaces-----------------------------------------------
usingnamespace std;
//------------globals/functions'n'classes-prototypes-----------------------------
struct node;
//-------------------------code--------------------------------------------------
struct node
{
string name;
int age;
node *next;
};
int main()
{
node *car1=new node; //first node declared and space allocated for it
car1->name="Aceix"; //assign "Aceix" to name under pointer(node) car1
car1->age=15;
car1->next=NULL; //set it to point to nothing in order to avoid problems
node *car2=new node; //second this way, i link the two noodes
car1->next=car2; //car1->next is given the address of car2 ie:the
//next node. in this way, i link the two.
car2->name="Kwesi";
car2->age=14;
car2->next=NULL;
node *car3=new node;
car2->next=car3;
car3->name="Smartie";
car3->age=17;
car3->next=NULL; //set car3->next to NULL to be safe
node *output=new node; //a temporary node for outputting the
//content of the linked list
output=car1; //assign the adress of car1-the first node-to output
while(output!=NULL) //runs until output=NULL
{
cout<<"Name: "<<output->name<<endl;
cout<<"Age: "<<output->age<<endl<<endl;
output=output->next; //changes what output points to to ensure
//that the loop finally prints every content
//and reach the end
}
cin.get();
system("CLS");
cout<<"Sorting from youngest to oldest...";
cin.get();
node *temp1=new node; //temporary nodes to help in sorting
node *temp2=new node;
temp2=temp1; //gives the address of temp1 to temp2
node *temp_car1=new node; //temporary node to handle some data
for(temp1=car1;temp1!=NULL;temp1=temp1->next)
{
for(temp2=temp1->next;temp2!=NULL;temp2=temp2->next)
{
if(temp1->age>temp2->age)
{
temp_car1->name=temp1->name; //gives temp_car->name
//the value of temp1->name
temp_car1->age=temp1->age;
temp1->name=temp2->name;
temp1->age=temp2->age;
}
}
}
system("CLS");
node *disp=new node;
cout<<"Content of linked list - arranged:\n\n"<<flush;
for(disp=car1;disp!=NULL;disp=disp->next)
{
cout<<"Name: "<<disp->name<<endl;
cout<<"Age: "<<disp->age<<endl<<endl;
}
cin.sync();
cin.get();
}
I am actually confused but I know the problem is in the loop.