linked list sort function only loops once
Posted
by
Tristan Pearce
on Stack Overflow
See other posts from Stack Overflow
or by Tristan Pearce
Published on 2012-04-02T23:18:54Z
Indexed on
2012/04/02
23:29 UTC
Read the original article
Hit count: 186
sorting
|linked-list
i have a singly linked list that i am trying to sort from least to greatest by price. here is what i have so far
struct part {
char* name;
float price;
int quantity;
struct part *next;
};
typedef struct part partType;
partType *sort_price(partType **item) {
partType *temp1 = *item;
partType *temp2 = (*item)->next;
if ( *item == NULL || (*item)->next == NULL )
return *item;
else {
while ( temp2 != NULL && temp2->next != NULL ){
if (temp2->price > temp2->next->price){
temp1->next = temp2->next;
temp2->next = temp2->next->next;
temp1->next->next = temp2;
}
temp1 = temp2;
temp2 = temp2->next;
}
}
return *item;
}
the list is already populated but when i call the sort function it only swaps the first two nodes that satisfy the condition in the if statement. I dont understand why it doesnt do the check again after the two temp pointers are incremented.
© Stack Overflow or respective owner