我有这种方法给我一个分段错误,我无法弄明白。我们必须删除与给定名称匹配的节点。
typedef struct node
{
int id;
char* name;
struct node* next;
} node;
node* rem_inorder(node** head, char* key_name)
{
node* temp = *head;
int found =0;
while(temp -> next != NULL &&!found)
{
if(temp -> name == key_name){
printf("works");
found = -1;}
else {
temp = temp ->next;}}
if(found == -1)
{return temp;}
else
{return NULL;}}
答案 0 :(得分:1)
对于初学者,该函数具有未定义的行为,因为对于空列表,表达式*head
的值可以等于NULL
。在这种情况下,此表达式temp -> next
将无效。
在搜索节点时,您还必须比较字符串而不是指针。
根据作业的描述,你必须从列表中删除找到的节点。
该功能可以通过以下方式定义
node * rem_inorder( node **head, const char *key_name )
{
node *target = NULL;
while ( *head && strcmp( ( *head )->name, key_name ) != 0 )
{
head = &( *head )->next;
}
if ( *head != NULL )
{
target = `*head;
*head = ( *head )->next;
target->next = NULL;
}
return target;
}`