33,311
社区成员
发帖
与我相关
我的任务
分享
#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函数里建立的链表是带哨兵(第一个节点)的单链表,因此在插入时应该是将新节点插入在哨兵节点的后面;
其他地方,我感觉不合适的地方一并修改了。参考一下吧,有问题可以继续提出来。