c - 链表中的 strncmp

标签 c sorting linked-list strncmp

该程序应该允许用户输入一些名称(直到用户希望继续),然后按升序显示这些名称。我使用了 strncmp 函数来比较 char 数组。但是,当运行此命令时,只有已排序名称列表的第一个和最后一个名称作为输出给出(这意味着列表已排序)。但我不明白为什么它们之间的名字没有显示。请帮我!谢谢。

#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();
}

最佳答案

将插入函数中的 else 更改为以下内容:

else
{
    temp = list;
    while(temp !=NULL && strncmp(temp->nm,name,10)<0)
    {
        prev=temp;
        temp=temp->next;
    }
    if(temp==NULL)
        prev->next=newnode;
    else
    {
        newnode->next=temp;
        prev->next=newnode;
    }

}

关于c - 链表中的 strncmp,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18680448/

相关文章:

c - 我对链表有一些问题

C:将新项分配给链表中的 "next"指针失败

c - C++ 函数和方法中的链表

c++ - 什么是 "pch.h"以及为什么需要将它作为第一个头文件包含在内?

c - 如何让 MinGW GCC 识别 size_t 的 %zu 格式说明符?

arrays - 如何查找/过滤具有最小正差的数组元素

在 Kotlin 中排序

c - 如何在 printf 中处理 '\0'?

c - 是否可以使用套接字使用连接代理?

ios - 如何在 iOS 中对带符号的数组进行排序?