c - 将节点添加到链表时,它会覆盖之前的所有节点
问题描述
添加多个不同字符串的节点后, print() 仅输出最后插入的节点的值。如果我插入了 10 个不同的节点,最后一个节点包含“FirstString”和“SecondString”,它将打印 10 次。我假设我的 insertLast 有问题,它用新的节点覆盖了所有以前的节点。
LinkedList* newLinkedList()
{
LinkedList* list;
list = (LinkedList*)malloc(sizeof(LinkedList));
(*list).head = NULL;
(*list).tail = NULL;
return list;
}
void insertLast( struct LinkedList* list, char* inCommand, char* inValue )
{
LinkedListNode* newNode;
printf( "Command:%s Value:%s\n", inCommand, inValue );
newNode = (LinkedListNode*)malloc(sizeof(LinkedListNode));
(*newNode).command = malloc( 10 * sizeof( char ) );
(*newNode).value = malloc( 3 * sizeof( char ) );
(*newNode).command = inCommand;
(*newNode).value = inValue;
newNode->next = NULL;
if( list->head == NULL )
{
list->head = newNode;
list->tail = newNode;
}
else
{
list->tail->next = newNode;
list->tail = newNode;
}
printf( "Start:%s %s \n", list->head->command, list->head->value );
printf( "End:%s %s \n", list->tail->command, list->tail->value );
}
void print( struct LinkedList* list )
{
LinkedListNode* current = list->head;
while( current!= NULL )
{
printf( "\n%s : %s \n", current->command, current->value );
current = current->next;
}
}
解决方案
将我的 insertLast() 更改为使用 strcpy,现在它似乎工作正常。:) 感谢您的回复。
void insertLast( struct LinkedList* list, char* inCommand, char* inValue )
{
LinkedListNode* newNode;
newNode = (LinkedListNode*)malloc(sizeof(LinkedListNode));
newNode->command = malloc( 10 * sizeof( char ) );
newNode->value = malloc( 3 * sizeof( char ) );
strcpy( newNode->command, inCommand );
strcpy( newNode->value, inValue );
newNode->next = NULL;
if( list->head == NULL )
{
list->head = newNode;
list->tail = newNode;
}
else
{
list->tail->next = newNode;
list->tail = newNode;
}
}
推荐阅读
- spring - 如何比较 Mono、Flux 中的相似数据
- php - 如何将大量收集和自定义数据传递到laravel中的另一条路线
- javascript - 如何在 gatsby graphql html 节点中获取特定元素
- line-breaks - 如何在openoffice中删除分段符
- list - 如何使用 OnClick 事件打印列表的内容?
- r - 堆积条形图,用于数据集的每一行
- python - 使用 Python 将文件直接上传到 FTP 服务器
- ios - 滚动视图通过打破约束工作
- javascript - 我在 nginx 中安装了 SSL 证书,但在浏览器中写入 url 告诉我:ERR_CONNECTION_REFUSED
- javascript - 在反应本机中的选择器值更改调用函数或数组