【问题标题】:Node deletion in linked list from beginning从头开始删除链表中的节点
【发布时间】:2020-09-09 02:03:27
【问题描述】:

我想删除第一个节点并返回被删除节点的值。但我收到了这个警告:

warning: assignment from incompatible pointer type [-Wincompatible-pointer-types]
 example=(**example).next;

所以,我的代码不起作用。谁能帮我解决这个问题?谢谢。

struct myStruct {
    int data;
    struct myStruct next;
}

int deleteNode(struct myStruct **example) {
    struct myStruct *temporary;
    if (temporary == NULL) { 
        emptyNode(temporary);   // this function only returns NULL
    }
    temporary = *example;
    example = (**example).next;
    free(temporary);

    return (**example).data;
}

【问题讨论】:

  • 除了 H.S.评论,您的temporary 未初始化,您在下一行检查NULL 值。
  • @H.S.对不起,我忘了在结构中写 *,它是 struct myStruct *next;但我仍然收到同样的警告。我无法理解这个问题。你能告诉我该怎么做吗?谢谢。

标签: c struct linked-list singly-linked-list function-definition


【解决方案1】:

此结构声明至少包含两个拼写错误。

struct myStruct 
{
  int data;
  struct myStruct next;
}

第一个是右大括号后没有分号。第二个是数据成员next必须有指针类型。

看来你的意思

struct myStruct 
{
  int data;
  struct myStruct *next;
};

至于错误信息则在本次作业中

example=(**example).next;

左侧操作数的类型为struct myStruct **,而右侧操作数的类型为struct myStruct *,并且这些指针类型不兼容。所以编译器会报错。

尽管如此,该函数在任何情况下都是无效的,因为您使用的是未初始化的变量,例如

struct myStruct *temporary;
if(temporary==NULL) 
//...

函数接口不好。因为不清楚函数在被空列表调用时返回什么。

函数可以通过以下方式声明和定义。

int deleteNode( struct myStruct  **example, int *data )
{
    int success = *example != NULL;

    if ( success )
    {
        struct myStruct *temporary = *example;
        *example = ( *example )->next;
        *data = temporary->data;
        free( temporary );
    }

    return success;
}

并且可以如下图这样调用

#include <stdio.h>
#include <stdlib.h>

struct myStruct 
{
    int data;
    struct myStruct *next;
};

int deleteNode( struct myStruct  **example, int *data )
{
    int success = *example != NULL;

    if ( success )
    {
        struct myStruct *temporary = *example;
        *example = ( *example )->next;
        *data = temporary->data;
        free( temporary );
    }

    return success;
}


int main(void) 
{
    struct myStruct *head = 0;

    //  fill the list

    int data;

    if ( deleteNode( &head, &data ) )
    {
        printf( "The deleted value is %d\n", data );
    }
    else
    {
        puts( "The list is empty." );
    }

    return 0;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-08
    • 2015-05-08
    • 1970-01-01
    • 2017-10-21
    相关资源
    最近更新 更多