Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linked List Sorting with Strings In C

I have a struct, with a Name and a single Node called nextName

It's a Singly Linked list, and my task is to create the list, based on alphabetical order of the strings.

So iff i enter Joe Zolt and Arthur i should get my list structured as

Joe

Than

Joe Zolt

Than

Arthur Joe Zolt

I'm having trouble implementing the correct Algorithm, which would put the pointers in the right order.

This is What I have as of Now. Temp would be the name the user just entered and is trying to put into the list, namebox is just a copy of my root, being the whole list

 if(temp != NULL)
      {
              struct node* namebox = root;
              while (namebox!=NULL && (strcmp((namebox)->name,temp->name) <= 0))
              {
                      namebox = namebox->nextName;
                      printf("here");
                 }
                temp->nextName = namebox;
    namebox = temp;
    root = namebox;

This Works right now, if i enter names like CCC BBB than AAA

I Get Back AAA BBB CCC when i print

But if i put AAA BBB CCC , When i print i only get CCC, it cuts the previous off.

Edit:

Can someone show me what the code would look like, i cant get it down.

like image 283
GreenMethod Avatar asked Sep 02 '25 05:09

GreenMethod


1 Answers

When you enter AAA, BBB and then CCC namebox is always NULL when while loop finishes.

And then you are doing:

// namebox is null
temp->nextName = namebox;
// namebox = CCC
namebox = temp;
// root = CCC
root = namebox;

So that's why you are getting only CCC.

Now, what you need to do in those cases is make sure CCC is added at the end of the list and do not change root.

like image 149
Pablo Santa Cruz Avatar answered Sep 04 '25 23:09

Pablo Santa Cruz