刚学到单链表,设计输出多项式的函数时出现了Segmentetion fault报错,查了一下好像是因为指针没有初始化,但是不知道是哪个指针没有初始化(按理说应该都初始化过了才对
#include <stdio.h>
#include <stdlib.h>
struct node{
int c;//系数
int e;//指数
struct node *next=NULL;
};
void read(node *head){
head=(struct node*) malloc (sizeof(node));
head->next=NULL;
node *q;
int c,e;
while(1){
scanf("%d %d",&c,&e);
if(c==0){
return;
}
else{
q=(struct node*) malloc (sizeof(node));
q->c=c;
q->e=e;
q->next=head->next;
head->next=q;
head=q;
}
}
}//读入多项式
void print(node *head){
if(head->next->e==0){
printf("%d",head->next->c);
}
else{
printf("%dx^%d",head->next->c,head->next->e);
}//先输出第一项
head=head->next;
while(head->next!=NULL){
if(head->next->c>0){
if(head->next->e==0){
printf("+%d",head->next->c);
}
else{
printf("+%dx^%d",head->next->c,head->next->e);
}
}
else if(head->next->c<0){
if(head->next->e==0){
printf("%d",head->next->c);
}
else{
printf("%dx^%d",head->next->c,head->next->e);
}
}
else;
head=head->next;
}
}//输出多项式
int main(){
node *f,*g,*h;
read(f);
read(g);
print(f);
return 0;
}