嗨我希望实现一个简单的链表和所有的值到列表的末尾。虽然这么简单,但我无法做到这一点。你能告诉我我在哪里做错了吗?最初我正在声明一个指针并为其分配NULL值。后来在每次迭代中,我都将内存分配给最初为NULL的指针。实现简单的链接列表
#include <stdio.h>
#include <malloc.h>
struct node{
int a;
struct node* next;
};
struct node* insert(struct node* start,int value);
void print(struct node* head);
int main()
{
int a;
struct node* head = NULL;
while(scanf("%d",&a) != EOF)//taking input
{
head = insert(head,a);
print(head);
}
return 0;
}
struct node* insert(struct node* start,int value)
{
struct node* head = start;
while(start != NULL)
{
start = start->next;//getting upto the end of the linked list
}
start = (struct node*)malloc(sizeof(struct node));//allocating memory at the end
start->a = value;
start->next = NULL;
if(head == NULL)
{
return start;//for the base case when list is initally empty
}
return head;
}
void print(struct node* head)
{
while(head != NULL)
{
printf("%d\n",head->a);
head = head->next;
}
return;
}
[似曾相识](http://stackoverflow.com/q/21762488/369450) – cpburnz
请注意'malloc.h'不达标。你应该使用'stdlib.h' – ajay
好的,我会在之后记住这一点。谢谢 –