Here is one method you could use to sort your linked list alphabetically:
(I haven't tested this specific code but the idea is sound)
First, push each node into an array of nodes:
Node **array = new Node*[size];
Node *temp = head_ptr;
while(temp)
{
Node[i] = temp;
temp = temp->next;
}
Now sort your array of Nodes based on the first letter of each name:
#include<algorithm>
//This function sorts to ascending order
sort(Node[0]->name[0], Node[size]->name[0]); Now.. all you have to do is include a provision on what to do if the first 2 letters of a person's name are the same.
Once you are done with all your sorting operations, turn the array of nodes back into a linked list. Make each node of the newly sorted list point to the next node in line by resetting all the *next pointers:
head_ptr = Nodes[0];
for(int i=0; i<size-1; i++)
Nodes[i]->next = Nodes[i+1];
That's it. You now have a head_ptr that points to beginning of a sorted linked list.
Clinton Portis
Practically a Posting Shark
833 posts since Oct 2005
Reputation Points: 237
Solved Threads: 118