In: Computer Science
Write a C program that creates and prints out a linked list of strings.
• Define your link structure so that every node can store a string of up to 255 characters.
• Implement the function insert_dictionary_order that receives a word (of type char*) and inserts is into the right position.
• Implement the print_list function that prints the list.
• In the main function, prompt the user to enter strings (strings are separated by white-spaces, such as space character, tab, or newline).
• Read and insert every string into the link list until you reach a single dot “.” or EOF.
• Print the list. Use scanf to read strings. Use strcpy() for copying strings.
Here is a sample text input:
This is a sample text. The file is terminated by a single dot: .
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
//defining node structure
typedef struct node
{
char data[255];//can store upto 255 characters
struct node *next;
}Node;
Node *head=NULL;//initially linked list is empty
//method to insert in sorted order
void insert_dictionary_order(char *a)
{
Node *n = (Node*)malloc(sizeof(Node));//creating new
node
strcpy(n->data,a);//reading data
n->next=NULL;
Node *temp=head,*prev=NULL;
if(temp==NULL)
{
head=n;
}
else
{//inserting in right position
while(temp!=NULL)
{
if(0<strcmp(temp->data,a))
break;
prev=temp;
temp=temp->next;
}
if(prev==NULL)
{
n->next=head;
head=n;
}
else
{
n->next=prev->next;
prev->next=n;
}
}
}
//method to print all words in list
void print_list()
{
Node *temp=head;
while(temp!=NULL)
{
printf("%s ",temp->data);
temp=temp->next;
}
printf("\n");
}
int main()
{
printf("Enter words seperated by spaces:(. or EOF to
stop):\n");
do
{
char s[255];
scanf("%s",s);
if(strcmp(s,".")==0 ||
strcmp(s,"EOF")==0)
{
insert_dictionary_order(s);//adding to list
break;
}
else
{
insert_dictionary_order(s);//adding to list
}
}
while(1);
//now printing list
print_list();
return 0;
}
output:
Enter words seperated by spaces:(. or EOF to stop):
This is a sample text. The file is terminated by a single dot:
.
. The This a a by dot: file is is sample single terminated
text.
Process exited normally.
Press any key to continue . . .