DingSJi 2021-06-04 15:25 采纳率: 0%
浏览 19

C语言链表插入节点未知错误

想在第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;
	
}

 

 

  • 写回答

3条回答 默认 最新

  • CSDN专家-link 2021-06-04 16:00
    关注

    insert(head,0);改成head = insert(head,0);就可以了

    你这个函数只能用返回值改变head地址,参数不能

    评论

报告相同问题?

悬赏问题

  • ¥30 模拟电路 logisim
  • ¥15 PVE8.2.7无法成功使用a5000的vGPU,什么原因
  • ¥15 is not in the mmseg::model registry。报错,模型注册表找不到自定义模块。
  • ¥15 安装quartus II18.1时弹出此error,怎么解决?
  • ¥15 keil官网下载psn序列号在哪
  • ¥15 想用adb命令做一个通话软件,播放录音
  • ¥30 Pytorch深度学习服务器跑不通问题解决?
  • ¥15 部分客户订单定位有误的问题
  • ¥15 如何在maya程序中利用python编写领子和褶裥的模型的方法
  • ¥15 Bug traq 数据包 大概什么价