Overview In this lab, we create an application which allows the user to build a
ID: 3811678 • Letter: O
Question
Overview In this lab, we create an application which allows the user to build a sorted list of strings. The program will perform the following action Prompt the enter 2. Call a function to insert that string, in alphabetic order, into a linked list. 3. the user did not enter a string, print the list in order and terminate. Specifications Use this structure and constant for the linked list node: #define MAx STR LEN 80 struct link node char node str MAX STR LEN struct link node next, Your solution should incorporate the following functions This function is used to compare two nodes. The return values are: //-1 nl n2 0: nl +1 nl n2 int compare node struct link node .nl, struct link node n2 This function is used to add a new node into the alphabetically sorted linked list. The head of the list is pointed to by list The return value is the (possibly new) head pointer. struct link node *add node struct link node .list, struct link node nodeExplanation / Answer
please refer below code
#include<stdlib.h>
#include<stdio.h>
#include<string.h>
#define MAX_STR_LEN 80
struct link_node
{
char node_str[MAX_STR_LEN];
struct link_node *next;
};
int compare_node(struct link_node *n1, struct link_node *n2)
{
if(strcmp(n1->node_str ,n2->node_str) < 0)
return -1;
else if(strcmp(n1->node_str ,n2->node_str) == 0)
return 0;
else
return 1;
}
struct link_node *add_node(struct link_node *list, struct link_node *node)
{
struct link_node *prev = NULL;
struct link_node *current = list;
while(current && (compare_node(current,node) < 0 ))
{
prev = current;
current = current->next;
}
if(prev == NULL)
list = node;
else
prev->next = node;
return list;
}
void print_list(struct link_node *list)
{
struct link_node *current;
current = list;
while(current != NULL)
{
printf("%s ", current->node_str);
current = current->next;
}
}
int main()
{
struct link_node *list = NULL;
char test[MAX_STR_LEN];
struct link_node *n;
printf("Enter the strings in each line and to terminate use blank line ");
while(strcmp(fgets(test,80,stdin), "") != 0)
{
n = (struct link_node *)malloc(sizeof(struct link_node));
list = add_node(list,n);
}
print_list(list);
return 0;
}
Please refer below output
Enter the strings in each line and to terminate use blank line
Ken Arnold
Tony Montiel
Boba Fett
Hoban Washburne
Neil Armstrong
Boba Fett
Hoban Washburne
Ken Arnold
Neil Armstrong
Tony Montiel
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.