gpt4 book ai didi

c - 当向链表添加一个节点时,它会覆盖之前的所有节点

转载 作者:行者123 更新时间:2023-11-30 18:11:01 24 4
gpt4 key购买 nike

添加多个具有不同字符串的节点后,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;
}
}

关于c - 当向链表添加一个节点时,它会覆盖之前的所有节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52889072/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com