There is a bit of a mis-mash here - a mix of C (char array instead of std::string) and C++ style programming (cout). For such a program, I doubt the performance requires the use of char arrays over std::string.
So... C++ STL already contains a doubly linked list -
list<>
.
If your intention is to create your own linked list, rather than use an in-built one, the following probably
has no use. However, the following "simplifies" (this is C++!) what you trying to do.
Instead of creating a structure that contains a pointer to the next node, you could remove that pointer member and include the following:
#include <list>
list<node*> personList;
Looking at the code, the Insert is really an Append. Assuming this, the following code performs this:
void Insert()
{
node* person = new node();
char name[10];
cout<<endl;
cout<<"Enter Your name: ";
cin>>person->name;
cout<<"Enter Your mark: ";
cin>>person->mark;
cout<<endl;
personList.push_back(person);
}
Sorting is far easier to work with:
bool comparePeople(node* first, node* second)
{
return (first->mark > second->mark);
}
void SortList()
{
if (personList.empty())
cout<<"List empty"<<endl;
else
{
personList.sort(comparePeople);
cout<<"Sorted list: "<<endl;
}
}
To output, you would do the following, instead of using the while loop:
int i = 1;
for (list<node*>::iterator it = personList.begin(); it != personList.end(); ++it)
{
cout<<i<<setw(10)<<(*it)->name<<setw(10)<<(*it)->mark<<endl;
++i;
}
(if you like extra functors, or can use lambda expressions (C++0x support required), you should use
for_each
instead)
Finally, which is what you have to work out yourself, there are 2 errors that need to be worked upon:
1) You can choose 4 to exit, but the application never exits
2) You must delete all objects you create (
person
in
Insert
). This should be before the "return 0" in
main
. I would suggest using
for_each
for this...