hello,

i have tired to sort my link list but unfortunately i can't seem to get it working.
The problem i having with the sort function is that it will sort the function when i enter a member to the list at the end except for the head. Also when i just want to sort the list it just deletes the node that need to be swap.

This is the struct so you have an idea how the linked list is set up.

/*setting up structure*/
 struct member_account{
     char member_last[MAX_LENGTH ];
     char member_first[MAX_LENGTH];
     double member_balance;
     struct member_account *next;
};

this is the sort funciton:

/*function sorts the list by last name or balance*/ 
struct member_account *sort(struct member_account *list){
 struct member_account *lst, *tmp = list, *prev, *potentialprev = list;
    int i, j, n = 0;
 
    //determine total number of nodes
    for (;tmp->next; tmp=tmp->next)
    {
        n++;
    }
 
    for (i=0; i<n-1; i++) 
    {
        for (j=0,lst=list; lst && lst->next && (j<=n-1-i); j++)
        {
            if (!j)
            {
                //at beginning, so treat start 
                //node as prev node
                prev = lst;
            }
 
            //compare the two nodes
            if ( strcmp ( lst->member_last, lst->next->member_last ) == 1 ) 
            {  
                //swap the nodes
                tmp = (lst->next?lst->next->next:0);
 
                if (!j && (prev == list))
                {
                    //do not have any special sentinal nodes
                    //so change beginning of the list to point 
                    //to the smallest swapped node
                    list = lst->next;
                }
                potentialprev = lst->next;
                prev= lst->next;
                lst= prev->next;
                tmp = lst->next;
                
                potentialprev->next= lst; 
                lst->next=prev; 
                prev->next=tmp; 
            }
            else
            {
                lst = lst->next;
                if(j)
                {
                    //keeping track of previous node, 
                    //for swapping nodes this is required
                    prev = prev->next;
                }
            }     
        } 
    }
    return list;

}

hello,

i have tired to sort my link list but unfortunately i can't seem to get it working.
The problem i having with the sort function is that it will sort the function when i enter a member to the list at the end except for the head. Also when i just want to sort the list it just deletes the node that need to be swap.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.