关于malloc函数的体会
在做PAT练习题的时候,体会到malloc函数申请的空间
对于一个结构体
struct Node{
int cof; //系数
int exp; //指数
List next;
};申请一个空间
List L0=(List)malloc(sizeof(struct Node)); //L0->next=NULL; L0->next是空节点 如果想要去除 就要加上L0->next;
于是乎得出含头节点的链表生成
List read(){
int N;
List L0=(List)malloc(sizeof(struct Node));
head=L0;
scanf("%d",&N);
if(N){
for(int i=0;i<N;i++){
List node=(List)malloc(sizeof(struct Node));
scanf("%d %d",&(node->cof),&(node->exp));
L0->next=node;
L0=node;
}
L0->next=NULL;
}
return head;
}不含头节点的生成链表:
List read(){
int N;
List L0=(List)malloc(sizeof(struct Node));
head=L0;
scanf("%d",&N);
if(N){
for(int i=0;i<N;i++){
scanf("%d %d",&(L0->cof),&(L0->exp));
if(i==N-1){
L0->next=NULL;
}else{
List node=(List)malloc(sizeof(struct Node));
L0->next=node;
L0=node;
}
}
}
return head;
}
查看10道真题和解析