嗨我希望實現一個簡單的鏈表和所有的值到列表的末尾。雖然這麼簡單,但我無法做到這一點。你能告訴我我在哪裏做錯了嗎?最初我正在聲明一個指針併爲其分配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
好的,我會在之後記住這一點。謝謝 –