I am trying to use a bubble sort to sort a linked list. I can't just swap the values inside the nodes either. I've been drawing pictures trying to figure out how to do it myself without help, but I'm starting to get a head ache and can't figure out why this wont work.
void sort_ascending(struct node ** head){
int x;
struct node*temp;
struct node*temp2;
x = length(*head)+1; //checks if more than one node is in the list
if(x < 2){
printf("1 or less\n");
//free(temp);
return;
}
printf("longer than 1\n");
printf("%d %d\n", (*head)->val, (*head)->next->val);
if((*head)->val > (*head)->next->val){
printf("needs to sort!\n");
temp = (*head)->next->next; //sets temp to the node after the two nodes being swapped
printf("test1\n");
temp2 = (*head); //sets temp2 to the node1
printf("test2\n");
*head = (*head)->next; //changes head to point at node2 instead of node1
printf("test3\n");
(*head)->next = temp2; //sets node2 to point to node1
(*head)->next->next = temp; //sets node2 to point back into the list
printf("test4\n");
//free(temp);
}
}
Right now I'm just trying to sort two nodes. After I can get this working I'll make it into a loop. For some reason, it isnt even sorting the first two elements.
Here are some of my other functions to help with understanding:
struct definition:
struct node {
int val;
struct node *next;
};
other functions:
void push(struct node ** headRef, int data){
struct node* newNode = malloc(sizeof(struct node)); //alocates space on heap
printf("pushed node\n");
newNode->val = data;//sets data value
printf("%d\n", newNode->val);
newNode->next = *headRef; // The '*' to dereferences back to the real head
*headRef = newNode; // ditto
};
void print(struct node * head, int length){
int x = 0;
printf("tried to print\n");
//struct node*temp = head;
//while(head->next != NULL){
while (x < length + 1){
printf("ran loop\n");
printf("%d\n", head->val);
printf("got number\n");
head = head->next;
x++;
}
printf("done with loop\n");
}
int main(){
char ans;
int num;
struct node *head = NULL;
do {
do {
printf("Enter a number: ");
scanf("%d", &num);
push(&head, num);//Can change to append for back
printf("Do you want another num (y or n): ");
scanf("%1s", &ans);
} while (ans == 'y');
printf("Sort ascending or descending (a or d)? ");
scanf("%1s", &ans);
if(ans == 'a') sort_ascending(&head);
//else if(ans == 'd') sort_descending(&head);
print(head, length(head));
printf("Do you want to do this again (y or n)? ");
scanf("%1s", &ans);
if (ans == 'y') clear(&head);
} while (ans == 'y');
return 0;
}
int length(struct node* head){
int length = 0;
//struct node*temp = head;
printf("tried to find length\n");
while (head->next != NULL){
length++;
head = head->next;
}
printf("%d\n", length + 1);
return length;
}