创建链表,给链表加5个节点,最后为什么不能输出,能解释一下吗?
靓仔,你给ptr赋空间后又将其指向那个空的head了
第15行应该是head=ptr;
修改如下,供参考:
#include<stdlib.h>
#include<stdio.h>
struct list {
int data;
struct list* next;
};
typedef struct list node;
typedef struct list* link;
int main()
{
link ptr, head;
int num, i;
ptr = (link)malloc(sizeof(node));
head = ptr;
printf("Please input 5 number=>\n");
for (i = 0; i <= 4; i++)
{
scanf("%d",&num);
ptr->data = num;
ptr->next = (link)malloc(sizeof(node));
if (i == 4) ptr->next = NULL;
else ptr = ptr->next;
}
ptr = head;
while (ptr != NULL)
{
printf("The value is => %d\n",ptr->data);
ptr = ptr->next;
}
return 0;
}