## user543820

Hello!

I am writing a code of linked list in which user can insert or delete names but the list must remain sorted alphabetically. I have written the given piece of code by now but it is not correct. Please help me out.
I took help from this link:

{
node *temp;
temp = new node;

if(p== NULL)
{
temp->info= newname;
p=temp;
}
else
{
bool done=true;

while (p!=NULL)
{
if((p->info)>newname)
{
done=true;
break;
}
}
if(done==false)
{
node *anew;
anew=new node;

anew->info=newname;

{
tail=anew;
count++;
}
else
{
tail=anew;
count++;
}
}
}
}

## mike_2000_17 2,669

First of all, keeping a sorted linked-list is never useful, because it requires linear time for a look-up and linear time for insertion. Keeping it unsorted requires linear time for look-up and constant time for insertion, tha's much better. But I guess you are doing this as an exercise.

The algorithm you posted is very weird. Where is the logic in it? The variables names are incorrect (what is head, tail, count, and p, these are all undefined variables).

The pseudo-code for this algorithm is pretty simple and should be followed closely:
1) Create a new node X and store the string in it.
2) If the list is empty (head pointer == NULL),
then set the head node to X, and exit.
3) Find the node A in the list whose name is smaller than X->name, but whose next node is either NULL or with name larger than X->name.
4) If A->next == NULL ,
then A is the last node in the list and X simply is appended at the end of the list, by setting A->next = X; .
5) If A->next != NULL ,
then insert X between A and A->next, i.e. set X->next = A->next; and set A->next = X; .
6) If you are keeping track of the tail node, then, if tail->next != NULL , set tail = tail->next; .

That's all. Your algorithm looks nothing like the above. Also, you should not have more than one occurrence of new node; , because you are only adding one node, this is a clear indication that the logic is broken.