C program gcc compiler dont use conio.h we must store the list of strings as a l
ID: 3606106 • Letter: C
Question
C program gcc compiler dont use conio.h
we must store the list of strings as a linked list of strings, each put in a “struct” object
struct String {
char *s;
struct String *next;
}
struct String *list;
Input: A list of strings, separated by a semicolon, ending by EOF. Please note that: Some strings have “new line” (‘ ’ <> ) Output:The list of strings in the ascending order of size of strings, separated by a “new line” (‘ ’ <> )
The code must implement the following functions:
• void get_strings(struct String *list): the function reads from “stdin” a list of strings and put them in the linked list “list”
• void sort_strings(struct String *list): this function is to ascendingly sort strings placed “list”
• void show_strings(struct String *list): this function prints the strings stored “list” to “stdout”
sample input: abc;def;1234;12
output:
sample input: ;;;;
output:
Explanation / Answer
Here is the complete solution of your problem .Feel free to Ask your dobuts if you have.Thanks.
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
struct String {
char *data;
struct String *next;
};
void append(struct String** head_ref, char *new_data)
{
/* 1. allocate node */
struct String* new_node = (struct String*) malloc(sizeof(struct String));
struct String *last = *head_ref; /* used in step 5*/
/* 2. put in the data */
new_node->data = new_data;
/* 3. This new node is going to be the last node, so make next of
it as NULL*/
new_node->next = NULL;
/* 4. If the Linked List is empty, then make the new node as head */
if (*head_ref == NULL)
{
*head_ref = new_node;
return;
}
/* 5. Else traverse till the last node */
while (last->next != NULL)
last = last->next;
/* 6. Change the next of last node */
last->next = new_node;
return;
}
void get_strings(struct String **list){
struct String* start= *list;
char *string;
char ch[10000];
//scanf("%s",ch);
scanf ("%[^ ]%*c", ch);
string = strdup(ch);
char* token;
while ((token = strsep(&string, ";"))!= NULL)
append(list,token);
}
void sort_strings(struct String *list){
int swapped, i;
struct String *ptr1=list;
struct String *lptr = NULL;
char* temp;
/* Checking for empty list */
if (ptr1 == NULL)
return;
do
{
swapped = 0;
ptr1 = list;
while (ptr1->next != lptr)
{
if ( strcmp(ptr1->data,ptr1->next->data) > 0)
{
//swap(&ptr1, &ptr1->next);
temp = ptr1->next->data;
ptr1->next->data =ptr1->data;
ptr1->data = temp;
swapped = 1;
}
ptr1 = ptr1->next;
}
lptr = ptr1;
}
while (swapped);
}
void show_strings(struct String *list){
while (list != NULL)
{
printf(" %s ", list->data);
list = list->next;
}
}
int main() {
struct String* head=NULL;
get_strings(&head);
sort_strings(head);
show_strings(head);
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.