So I have a linked list that contains two elements, a 3 character string that is read in, and an integer value. I need to sort the strings by their respective int values in a descending fashion. I'll link the whole block of code and then point out exactly where I'm getting stuck.
The code runs fine until it hits the sort() function. Then it gets caught in some infinite loop. The program is supposed to end when the user input string is 'end'.
void sort() {
struct node *ptr1, *ptr2;
ptr1 = ptr2 = head;
while(ptr1 != NULL){
ptr2 = ptr1;
while(ptr2 != NULL) {
if(ptr1->val < ptr2->val){
ptr2 = ptr2->next;
}
}
}
}
int main(void) {
char str[CMDSIZE];
head = NULL;
struct node *temp;
int randomnumber;
randomnumber = (rand() % 10) + 1;
while(strcmp(str, "end") != 0) {
printf("Enter your command: ");
fflush(stdout);
scanf("%[^\n]%*c", str);
insert(str, randomnumber);
randomnumber = (rand() % 10) + 1;
}
sort();
print();
}
Full code below:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define CMDSIZE 4
struct node
{
char cmd[4];
int val;
struct node *next;
};
struct node *head = NULL;
struct node *curr = NULL;
void insert(char command[], int x) {
struct node *temp;
temp = (struct node*)malloc(sizeof(struct node));
strcpy(temp->cmd, command);
temp->val = x;
temp->next = head;
head = temp;
}
void print() {
struct node *temp;
temp = head;
printf("\n Linked List Contents : \n");
while(temp!=NULL){
printf(" Node contains :\n %s %d \n", temp->cmd, temp->val);
temp=temp->next;
}
}
void sort() {
struct node *ptr1, *ptr2;
ptr1 = ptr2 = head;
while(ptr1 != NULL){
ptr2 = ptr1;
while(ptr2 != NULL) {
if(ptr1->val < ptr2->val){
ptr2 = ptr2->next;
}
}
}
}
int main(void) {
char str[CMDSIZE];
head = NULL;
struct node *temp;
int randomnumber;
randomnumber = (rand() % 10) + 1;
while(strcmp(str, "end") != 0) {
printf("Enter your command: ");
fflush(stdout);
scanf("%[^\n]%*c", str);
insert(str, randomnumber);
randomnumber = (rand() % 10) + 1;
}
sort();
print();
}
I use random 3 character strings for the input until I type 'end' and the sort function runs.
Output with sort():
Enter your command: lll
Enter your command: ooo
Enter your command: man
Enter your command: bmi
Enter your command: end
Output without sort():
Linked List Contents :
Node contains :
end 9
Node contains :
two 4
Node contains :
one 10
Node contains :
lll 8