带有头节点的链表插入问题
InsertNode函数:error C2223: left of '->next' must point to struct/union
p、q均为结构体指针,为什么还会出现这样的错误?
程序代码:#include<stdio.h>
#define datatype int
struct node
{
datatype dd;
struct node *next;
};
typedef struct node Node;
typedef struct node *Nodep;
Nodep init(Nodep L)
{
//初始化表,带有头节点
L=(Nodep)malloc(sizeof(Node));
if(L==NULL)
{
printf("申请内存失败!\n");
exit(0);
}
L->next=NULL;
return L;
}
datatype ListLength(Nodep L)
{
//返回表的长度
Nodep p=L->next;
int i=0;
while(p!=NULL)
{
i++;
p=p->next;
}
return i;
}
Nodep GetNode(Nodep L,datatype n)
{
//返回n位置的节点
Nodep p=L->next;
int i=1;
if((n<1)||(n>ListLength(L)))
{
printf("引用了错误的位置!\n");
exit(0);
}
while((p!=NULL)&&(i<n))
{
i++;
p=p->next;
}
return p;
}
datatype SearchNode(Nodep L,datatype value)
{
//返回值为value节点所在位置,如果没有找到则返回0
Nodep p=L->next;
int i=1;
while((p!=NULL)&&(p->dd!=value))
{
i++;
p=p->next;
}
if(p!=NULL)
return i;
else
return 0;
}
void LinkAddNode(Nodep L,datatype value)
{
//在链表尾部添加值为value的节点
Nodep p,q;
p=L->next;
q=(Nodep)malloc(sizeof(Node));
if(q==NULL)
{
printf("申请内存失败!\n");
exit(0);
}
q->dd=value; //新节点赋值
q->next=NULL; //新节点指向
if(p==NULL)
L->next=q; //如果是空表
else
{
while(p->next!=NULL) //循环找到最后一个节点
p=p->next;
p->next=q; //最后一个节点与新节点进行连接
}
}
void NodeDel(Nodep L,datatype value)
{
//删除值为value的节点
Nodep p,pre;
int i=SearchNode(L,value); //值为value节点的位置
if(i==0)
{
printf("错误的值!\n");
exit(0);
}
else
{
p=GetNode(L,i); //取得值为value的节点
pre=GetNode(L,i-1); //取得值为value的节点的前一个节点
pre->next=p->next; //重新连接
free(p); //释放占用的空间
}
}
void InsertNode(Nodep L,datatype n,datatype value)
{
//在表的第n的位置插入值为value的节点
if((n<1)||(n>ListLength(L))
{
printf("错误的位置!\n");
exit(0);
}
Nodep p=L->next;
Nodep q=(Nodep)malloc(sizeof(Node));
if(q==NULL)
{
printf("申请内存失败!\n");
exit(0);
}
q->dd=value; //新节点赋值
if(p==NULL)
{
L->next=q; //如果是空表则新节点成为第一个节点
q->next=NULL;
}
else
{
p=GetNode(L,n); //取得第n个位置的节点
q->next=p->next;
p->next=q;
}
}
void PutLink(Nodep L)
{
//输出链表的所有数据
Nodep p=L->next;
if(L->next==NULL)
printf("这是一个空表!");
else
{
while(p!=NULL)
{
printf(" %d ",p->dd);
p=p->next;
}
}
printf("\n");
}
int main(void)
{
Nodep L;
Nodep p;
int i;
L=init(L);
for(i=0;i<10;i++)
LinkAddNode(L,i);
printf("输出表的数据:");
PutLink(L);
printf("当前表共有%d个数据。\n",ListLength(L));
printf("值为5的数据在表中位置:%d\n",SearchNode(L,5));
NodeDel(L,5);
printf("将值为5的数据删除以后,新的表为:");
PutLink(L);
printf("当前表共有%d个数据。\n",ListLength(L));
printf("找到第3个位置的值:%d\n",GetNode(L,3)->dd);
printf("在第4个位置插入5:");
InsertNode(L,4,5);
PutLink(L);
return 0;
}[此贴子已经被作者于2015-10-18 07:41编辑过]





知道真相真是欲哭无泪啊!!