2022/4/7
Sapphire
解题思路:
链表废才学链表的第一题,哈哈哈
光看代码就可以了,我会有相应的解释
注意事项:
1.我有一问,这里如果不要typedef,那么在申请结点空间的时候应该用(Node*)malloc(sizeof(struct Node)),编译器不会报错,而且数据正常,但是提交答案时会显示编译错误,诚心发问,这是为什么呢?
参考代码:
#include<stdio.h>
#include<stdlib.h>
typedef struct Node
{
int real;
int unreal;
struct Node* next;
}node;//给Node这个结构体类型别名node
int main()
{
int n;
int sum1=0,sum2=0;
scanf("%d",&n);
struct Node *head;
head=(node*)malloc(sizeof(node));//这里的node就代表struct Node,node*代表struct Node*
for(int i=0;i<n;i++)
{
scanf("%d%d",&head->real,&head->unreal);
sum1+=head->real;
sum2+=head->unreal;
head->next=(node*)malloc(sizeof(node));//这里运用了头插法,让head的指针域指向一片空的node类型的区域
head=head->next;//再把头结点向前移一位,这时就能向这个新的区域输入数据了
}
head->next=NULL;//用完结点过后记得置空
printf("%d+%di\n",sum1,sum2);
return 0;
}
0.0分
0 人评分