该程序应允许用户输入一些名称(直到用户希望继续),然后按升序显示这些名称。我在比较 char 数组时使用了 strncmp 函数。但是当它运行时,只有排序后的名字列表的第一个和最后一个名字作为输出(这意味着列表已经排序)。但我不知道为什么不显示它们之间的名称。请帮我!谢谢你。
#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();
}