我正在尝试用C语言构建一个链表库。我已经完成了所有代码,但是有一个我找不到的错误,它使我的程序在几次测试中失败。
更具体地说。
每当我尝试删除包含某些数据的节点时,我的测试都会失败。节点未被删除,并打印了我的消息"此数据不在列表中"。
有人可以看看它并告诉我我错过了什么吗?
/* list_insertn: create a new node and insert it at the <n>th position,
where the head is at position 1
Parameters
- node*: a pointer to the head of a linked list
- char*: data to be stored in the new node
- int: the position in which to insert the new node
Return: a pointer to the head of the linked list */
node* list_insertn(node* list, char* input, int n){
// Base case
if(n <= 1){
// Create the new node and allocate memory for it
node *newNode = malloc(sizeof(struct s_node));
// Insert new node
newNode->next = list;
// Allocate enough memory for the data input
newNode->data = malloc(sizeof(char)*(strlen(input) +1));
// Place data in the node
strcpy(newNode->data, input);
return newNode;
}
//If we exceed list length append at the end
if(list->next == NULL){
list->next = list_insert_tail(NULL, input);
}
// Advance through the list if not at the specified position
list->next = list_insertn(list->next, input, n-1);
return list;
}
/* list_remove: remove the node containing specific data; if multiple nodes
contain the data, remove the node nearest to the head
Parameters
- node*: a pointer to the head of a linked list
- char*: data that, if found in one of the nodes in the list, indicates
the node to remove (in the case of multiple nodes containing the data,
remove the node nearest to the head)
Return: a pointer to the head of the linked list */
node* list_remove(node* list, char* input){
//As long as we have elemnts
if(list != NULL){
// We check to see if they have the same data
if(list->data == input){
// We remove the link
node *newNextNode = list->next;
// Remove the data
free(list->data);
// An remove the node itself when done
free(list);
return newNextNode;
}
//If it's not the correct data we move forward through the list
else{
// And check following nodes recursively
list->next = list_remove(list->next, input);
return list;
}
}
// But if we reach the end of the list
else{
// We print a warning message
printf("Specified data does not exist in any of the nodes");
return NULL;
}
}
由于学术安全,我必须删除部分代码。我只会留下有错误的部分。
我已经为您调试了这个。 修复:
-
在
list_insertn
中,将"If we exceed list length append at the end"
注释后面的整个if
语句替换为:if(list == NULL){ return list_insert_tail(list, input); }
-
在
list_remove
中,将"We check to see if they have the same data"
注释后面的测试替换为:if(strcmp(list->data, input) == 0){
-
作为一般清理,将所有
\n
实例修复为仅n
,并将任何缺少的n
字符添加到需要它们的各种printf
格式字符串的末尾。