【发布时间】: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