不能先:
p->next=NULL;
p=p->next;
再:
p=(struct Node*)malloc(sizeof(struct Node));
这样链表是不连接的,因为在p=p->next时,p就为空了,
错误例子:
struct Node *head=(struct Node *)malloc(sizeof(struct Node *));
struct Node *p=(struct Node *)malloc(sizeof(struct Node *));
head->element=5;
head->next=p;
p->element=2;
// p->next=(struct Node *)malloc(sizeof(struct Node *));
p->next=NULL;
p=p->next;
p=(struct Node *)malloc(sizeof(struct Node *));
p->element=3;
p->next=NULL;
正确操作:提前开辟空间
struct Node *head=(struct Node *)malloc(sizeof(struct Node *));
struct Node *p=(struct Node *)malloc(sizeof(struct Node *));
head->element=arr[0];
head->next=p;
p->element=2;
p->next=(struct Node *)malloc(sizeof(struct Node *));
// p->next=NULL;
p=p->next;
// p=(struct Node *)malloc(sizeof(struct Node *));
p->element=3;
p->next=NULL;