C语言实现List,出现错误,但是不知在哪里,求助一下。
#include <stdio.h>
#include <stdlib.h>
typedef int elemType ;
struct sNode{ /* 定义单链表结点类型 */
elemType data;
struct sNode *next;
};
/* 1.初始化线性表,即置单链表的表头指针为空 */
void initList(struct sNode* *hl)
{
*hl = NULL;
return;
}
/* 2.遍历一个单链表 */
void traverseList(struct sNode *hl)
{
while(hl != NULL){
printf("%5d", hl->data);
hl = hl->next;
}
printf(" ");
return;
}
/* 3.向单链表的末尾添加一个元素 */
void insertLastList(struct sNode* *hl, elemType x)
{
struct sNode *newP;
newP =(sNode *) malloc(sizeof(struct sNode));
if(newP == NULL){
printf("内在分配失败,退出运行! ");
exit(1);
}
/* 把x的值赋给新结点的data域,把空值赋给新结点的next域 */
newP->data = x;
newP->next = NULL;
/* 若原表为空,则作为表头结点插入 */
if(*hl == NULL){
*hl = newP;
}
/* 查找到表尾结点并完成插入 */
else{
struct sNode *p = NULL;
while(p->next != NULL){
p = p->next;
}
p->next = newP;
}
return;
}
int main(int argc, char* argv[])
{
int a[5]={1,2,3,4,5};
int i;
struct sNode *p;
initList(&p);
for(i = 0; i < 5; i++){
insertLastList(&p, a[i]);
}
traverseList(p);
}
insertLast中出现错误,但是不知道在哪里,希望大家能帮忙改一下,谢谢
[解决办法]
/* 查找到表尾结点并完成插入 */
else{
struct sNode *p = NULL;
while(p->next != NULL){
p = p->next;
}
struct sNode *p = NULL;不是等于NULL吧 应该是你表的头结点