我正在尝试实现一个在链接列表的开头插入名称的功能。问题在于最后一个节点中的数据将覆盖先前节点中的数据。这是我从代码中获得的输出:
/*
Number of names to insert:
3
Name to insert:
Tony
List is now Tony
Name to insert:
George
List is now George George
Name to insert:
Charles
List is now Charles Charles Charles
*/
请帮助我了解问题可能在哪里以及如何解决。这是代码。
#include <stdio.h>
#include <stdlib.h>
typedef struct node
{
char* word;
struct node* next;
}node;
void insert(char* s);
void print();
node* head = NULL;
int main(void)
{
int n;
char s[20];
puts("Number of names to insert:");
scanf(" %i", &n);
for (int i = 0; i < n ; i++)
{
puts("Name to insert: ");
scanf(" %s", s);
insert(s);
print();
}
}
void insert(char* s)
{
node* temp = malloc(sizeof(node));
temp->word = s;
temp->next = NULL;
if (head == NULL)
{
temp->next = head;
head = temp;
}
else
{
temp->next = head;
head = temp;
}
}
void print()
{
node* temp = head;
printf("List is now ");
while (temp != NULL)
{
printf("%s ", temp->word);
temp = temp->next;
}
printf("\n");
}
您需要为列表中插入的每个字符串分配内存。
该函数可以如下所示
void insert( const char *s )
{
node* temp = malloc( sizeof( node ) );
if ( temp != NULL )
{
temp->word = malloc( strlen( s ) + 1 );
strcpy( temp->word, s );
temp->next = head;
head = temp;
}
}
当列表将要停止存在时,应为每个节点中的字符串释放分配的内存。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句