c - 将字符串插入链表结构

标签 c

我正在尝试将字符串动态添加到链接列表中。 (我不知道会有多少根弦)。

这是迄今为止我发现的代码:

struct node
{
int data;
struct node *next;
}*start=NULL;
//------------------------------------------------------------

void creat()
{
char ch;
 do
 {
  struct node *new_node,*current;

  new_node=(struct node *)malloc(sizeof(struct node));

  printf("nEnter the data : ");
  scanf("%d",&new_node->data);
  new_node->next=NULL;

  if(start==NULL)
  {
  start=new_node;
  current=new_node;
  }
  else
  {
  current->next=new_node;
  current=new_node;
  }

 printf("nDo you want to creat another : ");
 ch=getche();
 }while(ch!='n');
}
//------------------------------------------------------------------

void display()
{
struct node *new_node;
 printf("The Linked List : n");
 new_node=start;
 while(new_node!=NULL)
   {
   printf("%d--->",new_node->data);
   new_node=new_node->next;
   }
  printf("NULL");
}

如果我想将字符串添加到链表结构中,我只需更改:

    struct node {
      int data;

至:

  struct node {
    char abc[256];

并将所有 %d 更改为 %s?就这么简单吗?

最佳答案

是啊!它也会起作用。但更好的方法是保留一个临时缓冲区来存储字符串输入。现在,每当您获得一个字符串时,只需动态分配(使用malloc())该数字字符+ 1 个字符到该指针。并使用 strcpy() 将缓冲的输入复制到其中。看看这个代码片段。

struct struct_name
{
   char *data;
    ....
};
char buffer[MAXBUFFERSIZE];
scanf("%s",buffer);
struct struct_name * temp= (struct struct_name*) malloc(sizeof(char)*(strlen(buffer)+1));
if(temp==NULL)
{
    //error.
}
strcpy(temp->data,buffer);
.....

关于c - 将字符串插入链表结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29129393/

相关文章:

c++ - 为什么这段代码打印0223?

c - "C"中的贪心算法

c - linux内核如何检查是否设置了粘滞位

c++ - 使用 visual studio 测量 RTT

c++ - Unix - 防止内存消耗失控导致 PC 崩溃?

objective-c - 使按钮暂停并播放声音代码错误

c - 在c中实现 union 比较的实用方法

stdint 的 int8_t 可以存在于没有 8 位字节的架构上吗?

c - 在 STM32F1 上的应用程序之间跳转

python - 在 C 中嵌入 python - 分发