The first approach to linked lists ever. As stated in the title, I'm trying to get a function that sorts a linked list's nodes by their int
value (val
).
But as the function gets called the program leaves me hanging.
Given my simple node struct:
struct node {
int val;
struct node* next;
};
This is the function that I hoped would do it:
void sort(struct node** head) {
struct node* curr = *head;
while (curr != NULL) {
struct node* next = curr->next;
while (next != NULL) {
if(curr->val > next->val) {
swap(&curr->val, &next->val);
// next = next->next;
}
next = next->next; // has to go here
}
curr = curr->next;
}
}
I acknowledge this might be confusing, but I tried to re-use the same logic as if I had to sort a vector (comparing each item as if I had an index). Thank you in advance for helping me.
EDIT: Just joking, I just noticed that I misconfigured the second while
. The next->next
node has to go outside the if condition