想在第0个节点处(最前面)添加一个节点,程序检查了好几遍实在看不出来错误,求大神指点!!
#include<stdio.h>
#include<stdlib.h>
struct node{
int id,mpoints;
struct node *next;
};
int main(){
struct node * creat(struct node * head,int n);
void print(struct node *head);
struct node *insert(struct node *head,int pos);
struct node *head=NULL;
head=creat(head,5);
print(head);
insert(head,0);
print(head);
return 0;
}
struct node * creat(struct node * head,int n){//构造节点
int i;
struct node *p,*q;
for(i=1;i<=n;i++){
q=(struct node*)malloc(sizeof(struct node));
printf("请输入第%d个会员id和积分:\n",i);
scanf("%d%d",&q->id,&q->mpoints);
q->next=NULL;
if(head==NULL)
head=q;
else
p->next=q;
p=q;
}
return head;
}
void print(struct node *head){//遍历节点
struct node *p=head;
printf("id\tmpoints\n");
while(p!=NULL){
printf("%d\t%d\n",p->id,p->mpoints);
p=p->next;
}
}
struct node *insert(struct node *head,int pos){//指定位置插入节点
struct node *p,*pNew,*q;
int i=0;
pNew=(struct node *)malloc(sizeof(struct node));
printf("请输入要插入的会员id和积分:\n");
scanf("%d%d",&pNew->id,&pNew->mpoints);
if(NULL==pNew)
{
printf("动态内存分配失败!\n");
exit(-1);
}
if (head==NULL){
pNew->next=NULL;
head=pNew;
return head;
}
if(pos<0){
printf("插入位置有错!\n");
return head;
}
if(pos==0){ //在最前面插入节点
pNew->next=head;
head=pNew;
return head;
}
p=head;
while(p!=NULL&&i<pos-1){
p=p->next;
++i;
}
if(p==NULL){
printf("插入位置有错!\n");return head;
}
q=p->next;
p->next=pNew;
pNew->next=q;
return head;
}