c语言链表插入有问题请教大佬们

qq_39263012 2018-01-17 04:59:28
请教一下大佬们,这段代码为什么不能正常在表头插入节点呀
#include<stdio.h>
#include<stdlib.h>
typedef struct node* nodepointer;
typedef struct node{
float data;
char a;
nodepointer next;
};
void main()
{
int i,j;
float data;
char a;
void shuchu(nodepointer);
nodepointer insert(nodepointer);
nodepointer head,temp,node,mmm;
node=(nodepointer)malloc(sizeof(nodepointer));
head=temp=node;
printf("请输入你想要的链表的个数");
scanf_s("%d",&i);
for(j=1;j<=i;j++)
{
printf("请输入第%d个节点的值",j);
scanf_s("%f",&data);
temp=(nodepointer)malloc(sizeof(nodepointer));
temp->data=data;
node->next=temp;
node=node->next;
}
temp->next=NULL;
shuchu(head);
printf("输入插入表头数据");
mmm=insert(head);
shuchu(mmm);
while(1);
}
nodepointer insert(nodepointer a)
{
nodepointer node;
float data;
node=(nodepointer)malloc(sizeof(nodepointer));
if(a){
scanf_s("%f",&data);
node->data=data;
node->next=a;
a=node;
return a;
}

}
void shuchu(nodepointer a)
{
for(;a=a->next;)
printf("%f\n",a->data);
}

...全文
520 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
自信男孩 2018-01-18
  • 打赏
  • 举报
回复
#include<stdio.h>
#include<stdlib.h>

typedef struct node* nodepointer;

struct node{
	float data;
	char a;
	nodepointer  next;
};

	void shuchu(nodepointer);
	nodepointer insert(nodepointer);
//void main()
int main()
{
	int i,j;
	float data;
	char a;
	nodepointer head,temp,node,mmm;
	node = (nodepointer)malloc(sizeof(struct node));
	head = temp = node;
	printf("请输入你想要的链表的个数");
	//scanf_s("%d",&i);
	scanf("%d",&i);
	for(j = 1; j<=i;j++)
	{
		printf("请输入第%d个节点的值",j);
		//scanf_s("%f",&data);
		scanf("%f",&data);
		temp=(nodepointer)malloc(sizeof(struct node));
		temp->data = data;
		node->next = temp;
		node = node->next;
	}
	temp->next=NULL;
	shuchu(head);
	printf("输入插入表头数据");
	mmm = insert(head);
	shuchu(mmm);

	return 0;
}
nodepointer insert(nodepointer phead)
{
	nodepointer node;
	float data;

	node = (nodepointer)malloc(sizeof(struct node));
	if (!node) {
		fprintf(stderr, "malloc error!\n");
		exit(0);
	}
	if(phead){
		//scanf_s("%f",&data);
		scanf("%f",&data);
		node->data = data;
		node->next = phead->next;
		phead->next = node;
		return phead;
	}

}
void shuchu(nodepointer phead)
{

	if (!phead)
		return;
	nodepointer pcur = phead->next;

	while (pcur) {
		printf("%f\n", pcur->data);
		pcur = pcur->next;
	}
}
参考一下吧 第一个问题:malloc申请的空间大小应该是sizeof(struct node);因为sizeof(nodepointer)长度是固定的,即指针的长度,而不是结构体的长度; 第二个问题:main函数里建立的链表是带哨兵(第一个节点)的单链表,因此在插入时应该是将新节点插入在哨兵节点的后面; 其他地方,我感觉不合适的地方一并修改了。参考一下吧,有问题可以继续提出来。
qq_39263012 2018-01-17
  • 打赏
  • 举报
回复
为什么我插入的第一结点输出结果是好像地址一样的东西
赵4老师 2018-01-17
  • 打赏
  • 举报
回复
数据结构对单链表进行数据排序 http://bbs.csdn.net/topics/392201633

33,311

社区成员

发帖
与我相关
我的任务
社区描述
C/C++ 新手乐园
社区管理员
  • 新手乐园社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧