如果您不想使用引用指针,则可以使用指向指针的指针。我的完整代码都象下面这样:
void insertAtEnd(struct node **p,int new_data)
{
struct node *new_node=(struct node *)malloc(sizeof(struct node));
new_node->data=new_data;
new_node->next=NULL;
if((*p)==NULL)//if list is empty
{
*p=new_node;
return;
}
struct node* last=*p;//initailly points to the 1st node
while((last)->next != NULL)//traverse till the last node
last=last->next;
last->next=new_node;
}
void printlist(struct node *node)
{
while(node != NULL);
{
printf("%d->",node->data);
node=node->next;
}
}
int main()
{
struct node *root=NULL;
insertAtEnd(&root,1);
insertAtEnd(&root,2);
insertAtEnd(&root,3);
insertAtEnd(&root,4);
insertAtEnd(&root,5);
printlist(root);
return 0;
}
了解需要以下两个变量的关键是认识问题:
- 结构节点** P:因为我们需要把它从根链接主节点中创建的节点。
- struct node * last:因为如果不使用,原始内容将随着while循环内下一个节点的内容而改变。最后只打印2个元素,最后2个节点,这是不需要的。
也许你可以添加一些说明... –