0

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;

}

Edited by johnhuge: n/a

1
Contributor
1
Reply
3
Views
6 Years
Discussion Span
Last Post by johnhuge
0

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 question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.