【问题标题】:request for member xxxx in something not a structure or union在非结构或联合的情况下请求成员 xxxx
【发布时间】:2014-02-09 19:58:22
【问题描述】:

我正在尝试编写一个函数来将插入节点添加到链表。函数参数是指向应该插入元素的节点的指针和元素的指针。我得到错误 以非结构或联合的形式请求成员“数据” 在非结构或联合的情况下请求成员“下一个”

next和data是链表中的两个字段

void INSERT(int element, struct Node** position)
{
    //If inserting at front
    if( *position==NULL){

            *position -> data = element;
            *position -> next = NULL;
            return;
    }

    //the node to be inserted is named temp
    struct Node *temp = (struct Node*)malloc(sizeof(struct Node));


    //create cell
    temp -> data = element;
    temp -> next = *position->next;

    *position-> next = temp;


}

struct节点的定义是

 struct Node
 {
    int data;//payload
    struct Node* next;
 };

main函数调用INSERT

int main()
{
    struct Node *head =(struct Node*)malloc(sizeof(struct Node));

    head -> data =5;
    head -> next  = NULL;

    INSERT(2,&head);
    INSERT(3,&head);



   PRINTLIST(&head);
    return 0;
 }

PRINTLIST 只打印列表。效果很好

【问题讨论】:

  • 忠告:在本帖中添加struct Node的定义,很快就会得到答案……
  • struct Node的定义是... ?
  • 如果*position == NULL需要先分配
  • 我刚刚添加了Node的定义
  • *position->next; --> (*position)->next;

标签: c pointers linked-list pass-by-reference


【解决方案1】:

大概是这样

void INSERT(int element, struct Node **position){
    struct Node *temp = (struct Node*)malloc(sizeof(struct Node));
    temp -> data = element;
    temp -> next = NULL;
    if( *position==NULL){
        *position = temp;
        return;
    }
    temp->next = (*position)->next;
    (*position)->next = temp;
}
//result : //5 -> 3 -> 2 : is inserted next to the head

【讨论】:

    猜你喜欢
    • 2017-10-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多