Thread: sort my linked list alphabetically

  1. #1
    Registered User
    Join Date
    Dec 2002
    Posts
    1

    sort my linked list alphabetically

    hello, I have a linked list and I want to add some things to it. I want to be able to sort my list alphabetically by the person's last name. I want it so that the user can see a list of last names in alphabetical order, so that she/he can than access that last name to see that persons record. That leads me to another thing i also want to be able to modify the person's record, for example change their gpa or thei advisors name.

    I have and example of a sorted link list in alphbetical order, I just dont know how to implent it to my program. I dont know where to put it or what to change on it so that it can fit my need.

    My program is at the top and the sample sorted list is at the bottom. Thankyou for your help.


    My program:

    #include <stdio.h>
    #include <stdlib.h>
    #include <malloc.h>
    #include <string.h>
    #include <ctype.h>
    #include <conio.h>

    void addNewAccount(void);
    void listAll(void);
    void deleteAccount(void);

    struct account {
    int number;
    char lastname[15];
    char firstname[15];
    char advisorname[15];
    char advisornum[15];
    char major[15];
    float gpa;
    struct account *next;
    };
    struct account *first,*current,*news;
    int anum = 0;

    void main()
    {
    char ch;

    /* Initialize all the pointers */

    first = (struct account *)NULL;
    current = (struct account *)NULL;
    news = (struct account *)NULL;

    do
    {
    puts("\nA - Add a student");
    puts("D - Delete a student");
    puts("L - List all students");
    puts("Q - Quit this program\n");
    printf("\tYour choice:");
    ch = toupper(getch());
    switch(ch)
    {
    case 'A':
    puts("Add new student\n");
    addNewAccount();
    break;
    case 'D':
    puts("Delete a student\n");
    deleteAccount();
    break;
    case 'L':
    puts("List All students\n");
    listAll();
    break;
    case 'Q':
    puts("Quit\n");
    default:
    break;
    }
    }
    while(ch != 'Q');
    }

    void addNewAccount(void)
    {
    char buffer[100];

    news = (struct account *)malloc(sizeof(struct account));

    /* Check to see if this is the first record
    * If so, then initialize all the pointers to this,
    * first structure in the database
    */

    if(first==(struct account *)NULL)
    first = current = news;

    /* Otherwise, you must find the end of the structure list
    * (Easily spotted by the NULL pointer) and add on the
    * new structure you just allocated memory for
    */

    else
    {
    current = first; //make the first record the current one
    //and loop through all records:

    while(current->next != (struct account *)NULL)
    current = current->next;

    //the last record is found
    current->next = news; //save the address of the new record
    current = news; //and make the current record the new one
    }

    /* Now, you just fill in the new structure */

    anum++;
    printf(" student number: %5i\n",anum);
    current->number = anum;

    printf("Enter student's last name: ");
    gets(current->lastname);

    printf("Enter students's first name: ");
    gets(current->firstname);

    printf("Enter advisors's name: ");
    gets(current->advisorname);

    printf("Enter advisors's phone number: ");
    gets(current->advisornum);

    printf("Enter major: ");
    gets(current->major);

    printf("Enter student's GPA: ");
    current->gpa = atof(gets(buffer));

    /* Finally, cap the new record with a NULL pointer
    * so that you know it's the last record:
    */

    current->next = (struct account *)NULL;
    }

    void listAll(void)
    {

    if(first==(struct account *)NULL)
    puts("There are no records to print!");
    else
    {
    current=first;
    do
    {
    printf("stundent #: %5i\n%-15s, %-15s\nadvisor: %-15s\nadvisor number: %-15s\nmajor: %-15s\ngpa: %1.2f\n",\
    current->number,\
    current->lastname,\
    current->firstname,\
    current->advisorname,\
    current->advisornum,\
    current->major,\
    current->gpa);
    }
    while((current=current->next) != (struct account *)NULL);
    }
    }

    void deleteAccount(void)
    {
    char ch;
    struct account *previous;

    if(first==(struct account *)NULL)
    puts("There are no records to delete!");
    else
    {
    current=first;
    do
    {
    printf("stundent #: %5i\n%-15s, %-15s\nadvisor: %-15s\nadvisor number: %-15s\nmajor: %-15s\ngpa: %1.2f\n",\
    current->number,\
    current->lastname,\
    current->firstname,\
    current->advisorname,\
    current->advisornum,\
    current->major,\
    current->gpa);
    printf("DELETE THIS RECORD?");
    ch = toupper(getch());
    if(ch=='Y')
    {
    puts("Yes!");
    if(current==first)
    {
    first=current->next;
    break;
    }
    else
    {
    previous->next = current->next;
    break;
    }
    }
    else
    {
    puts("No!");
    previous=current;
    }
    }
    while((current=current->next) != (struct account *)NULL);
    }
    }


    Sample program:

    #include <stdio.h>
    #include <string.h>

    int main()
    {
    struct oz {
    char actor[20];
    char character[30];
    int age;
    };
    struct oz cast[4] = {
    "Judy Garland", "Dorothy", 17,
    "Ray Bolger", "Scarecrow", 35,
    "Bert Lahr", "Cowardly Lion", 44,
    "Jack Haley", "Tin Woodsman", 40
    };
    struct oz *sorter[4];
    struct oz *swapper;
    int i,a,b,size;

    /* Initialize the pointer array */

    for(i=0;i<4;i++) {
    sorter[i] = &cast[i];
    }

    /* Sort the list (From Chapter 9)*/

    size = 4; /* the size of the array */
    for(a=0;a<size-1;a++)
    for(b=a+1;b<size;b++)
    if(strcmp(sorter[a]->actor,sorter[b]->actor)>0)
    {
    swapper = sorter[b];
    sorter[b] = sorter[a];
    sorter[a] = swapper;
    }

    /* Print the sorted list */

    printf("The Sorted Cast List:\n");
    for(i=0;i<4;i++) {
    printf("%s played the %s\n",sorter[i]->actor,sorter[i]->character);
    }

    return(0);
    }

  2. #2
    Registered User
    Join Date
    Nov 2002
    Posts
    29
    Im learning linked lists so I can't help you with that but to help other people give you advice.....use the code tags when posting code.

  3. #3
    wakenate05
    Guest
    Here is a simple linked list that will sort 5 different characters that you give it. Maybe you can use this to help you.
    Code:
    #include<stdlib.h>
    #include<stdio.h>
    #include<string.h>
    
    struct list{
    char ch;
    struct list *next_rec;
    };
    typedef struct list LIST;
    typedef LIST *LISTPTR;
    
    int main( void )
     {
        LISTPTR first = NULL;  /* head pointer */
        int i = 0;
        int ch;
        char trash[256];       /* to clear stdin buffer. */
    
        while ( i++ < 5 )      /* build a list based on 5 items given */
        {
           ch = 0;
           printf("\nEnter character %d, ", i);
    
           do
           {
               printf("\nMust be a to z: ");
               ch = getc(stdin);  /* get next char in buffer  */
               gets(trash);       /* remove trash from buffer */
           } while( (ch < 'a' || ch > 'z') && (ch < 'A' || ch > 'Z'));
    
           first = add_to_list( ch, first );
        }
    
       show_list( first );           /* Dumps the entire list */
       free_memory_list( first );    /* Release all memory */
       getch();
       return(0);
    }
    
    LISTPTR add_to_list(int ch, LISTPTR first){
    LISTPTR new_rec=NULL;
    LISTPTR tmp_rec=NULL;
    LISTPTR prev_rec=NULL;
    
    new_rec=(LISTPTR)malloc(sizeof(LIST));
    if(!new_rec){
        printf("Unable to allocate\n");
        getch();
        exit(1);}
    new_rec->ch=ch;
    new_rec->next_rec=NULL;
    if(first==NULL){
        first=new_rec;
        new_rec->next_rec=NULL;}
    else
    {
    if ( new_rec->ch < first->ch)
           {
              new_rec->next_rec = first;
              first = new_rec;
           }
           else   /* it is being added to the middle or end */
           {
              tmp_rec = first->next_rec;
              prev_rec = first;
    
             /* Check to see where link is added. */
    
              if ( tmp_rec == NULL )
              {
                  /* we are adding second record to end */
                  prev_rec->next_rec = new_rec;
              }
              else
              {
                 /* check to see if adding in middle */
                 while (( tmp_rec->next_rec != NULL))
                 {
                    if( new_rec->ch < tmp_rec->ch )
                    {
                       new_rec->next_rec = tmp_rec;
                       if (new_rec->next_rec != prev_rec->next_rec)
                       {
                          printf("ERROR");
                          getc(stdin);
                          exit(0);
                       }
                       prev_rec->next_rec = new_rec;
                       break;   /* link is added; exit while */
                    }
                    else
                    {
                      tmp_rec = tmp_rec->next_rec;
                      prev_rec = prev_rec->next_rec;
                    }
                 }
    
                 /* check to see if adding to the end */
                 if (tmp_rec->next_rec == NULL)
                 {
                    if (new_rec->ch < tmp_rec->ch ) /* 1 b4 end */
                    {
                       new_rec->next_rec = tmp_rec;
                       prev_rec->next_rec = new_rec;
                    }
                    else  /* at the end */
                    {
                       tmp_rec->next_rec = new_rec;
                       new_rec->next_rec = NULL;  /* redundant */
                    }
                 }
              }
           }
        }
        return(first);
     }
    
     /*========================================================*
      * Function: show_list
      * Purpose : Displays the information current in the list
      *========================================================*/
    
     void show_list( LISTPTR first )
    {
        LISTPTR cur_ptr;
      int counter = 1;
    
        printf("\n\nRec addr  Position  Data  Next Rec addr\n");
        printf("========  ========  ====  =============\n");
    
        cur_ptr = first;
        while (cur_ptr != NULL )
        {
           printf("  %X   ", cur_ptr );
           printf("     %2i       %c", counter++, cur_ptr->ch);
           printf("      %X   \n",cur_ptr->next_rec);
           cur_ptr = cur_ptr->next_rec;
        }
     }
    
     /*========================================================*
      * Function: free_memory_list
      * Purpose : Frees up all the memory collected for list
      *========================================================*/
    
     void free_memory_list(LISTPTR first)
     {
        LISTPTR cur_ptr, next_rec;
        cur_ptr = first;                 /* Start at beginning */
    
        while (cur_ptr != NULL)          /* Go while not end of list */
        {
           next_rec = cur_ptr->next_rec; /* Get address of next record */
           free(cur_ptr);                /* Free current record */
           cur_ptr = next_rec;           /* Adjust current record*/
      }
    }
    yea its long.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Reverse function for linked list
    By Brigs76 in forum C++ Programming
    Replies: 1
    Last Post: 10-25-2006, 10:01 AM
  2. Help with Insertion sort on a single linked list
    By goron350 in forum C++ Programming
    Replies: 4
    Last Post: 07-11-2005, 08:38 PM
  3. sort linked list using BST
    By Micko in forum C Programming
    Replies: 8
    Last Post: 10-04-2004, 02:04 PM
  4. Linked list with two class types within template.
    By SilasP in forum C++ Programming
    Replies: 3
    Last Post: 02-09-2002, 06:13 AM
  5. singly linked list
    By clarinetster in forum C Programming
    Replies: 2
    Last Post: 08-26-2001, 10:21 PM