strncmp in Linked List
This program should allow the user to input some names (until the user
wishes to continue.) and then display those names in ascending order. I
have used the strncmp function in comparing the char arrays. But when this
is run, only the 1st and last name of the sorted name list is given as the
output (which means, the list was sorted). But I cannot find out why the
names in between them aren't displayed. Please help me! Thank you.
#include <stdio.h>
#include <malloc.h>
#include <string.h>
char name[10];
int place;
struct node
{
char nm[10];
struct node *next;
}*newnode, *prev, *temp, *display, *current, *list;
void createlist()
{
list = NULL;
}
;
void insert()
{
newnode = (struct node*) malloc(sizeof(struct node));
printf("Enter the Name: ");
scanf("%s", &name);
strncpy(newnode->nm, name, 10);
newnode->next = NULL;
if (list == NULL )
{
list = newnode;
}
else if (strncmp(name, list->nm, 10) < 0)
{
newnode->next = list;
list = newnode;
}
else
{
temp = list;
place = 0;
while (temp != NULL && place == 0)
{
if (strncmp(name, temp->nm, 10) >= 0)
{
prev = temp;
temp = temp->next;
}
else
{
place = 1;
}
newnode->next = prev->next;
prev->next = newnode;
}
}
}
void displayname()
{
if (list == NULL )
printf("\n\nList is empty");
else
{
display = list;
while (display != NULL )
{
printf("%s\n", display->nm);
display = display->next;
}
}
}
int main()
{
char choice;
choice == 'y';
createlist();
do
{
insert();
printf("Do you want to continue? ");
scanf("%s", &choice);
} while (choice = 'y' && choice != 'n');
displayname();
}
No comments:
Post a Comment