my program prints an extra zero in the end, and I tried removing the malloc in main and allocate inside the function but it just produces a segfault
Code:
#include<stdio.h>
#include<stdlib.h>
typedef struct term_tag{
int coef;
int exponent;
struct term_tag *next;
}pnode;
typedef struct expression{ //expansion
int num_terms;
int exponent;
pnode *terms;
}expr;
void printlist();
// void printexpr();
void createpoly();
void nodesort();
int addpoly();
void display();
int main(){
pnode *poly1 = (pnode *)malloc(sizeof(pnode));
pnode *poly2 = (pnode *)malloc(sizeof(pnode));
// expr *expr1 = (expr *)malloc(sizeof(expr));
// expr *expr2 = (expr *)malloc(sizeof(expr));
FILE *fp;
fp = fopen("input.txt","r");
// CASE COUNT
if(fp != NULL){
createpoly(&poly1, &poly2, &fp);
printf(" ");
printlist(poly1);
printf("\n+ ");
printlist(poly2);
printf("\n");
}
return 0;
}
void printlist(pnode * pptr) { //pass the test list as parameters
pnode * temp = pptr; //temp same as where head is pointing
while (temp->next != NULL) {
if(temp->exponent == 1) //won't print exponent one anymore
printf("%dx + ",temp->coef);
if(temp->exponent == 0) //won't print x if expo is 0
printf("%d + ",temp->coef);
else
printf("%dx^%d + ",temp->coef,temp->exponent);
temp = temp->next;
} //repeat till NULL meaning end of list
if(temp->next == NULL){
if(temp->exponent == 0){
printf("%d", temp->coef);
return;
}
if(temp->exponent == 1){
printf("%dx", temp->coef);
return;
}
else{
printf("%dx^%d", temp->coef, temp->exponent);
return;
}
}
printf("\n");
}
void createpoly(pnode **pptr1, pnode **pptr2, FILE **fptr){
int case_count, case_num, term_count;
fscanf(*fptr,"%d",&case_count);
// CASES
while(case_count > 0){
fscanf(*fptr, "%d", &case_num); //read line then move to new line
// ADDITION
if(case_num == 1){
fscanf(*fptr, "%d", &term_count); //store line content(ie term count to var)
pnode *temp = *pptr1;
while(term_count > 0){
if(temp == NULL){
temp = (pnode*)malloc(sizeof(pnode));
temp->next = NULL;
}
while(temp->next != NULL){
temp = temp->next;
}
if(temp->next == NULL){
temp->next = (pnode *)malloc(sizeof (pnode));
fscanf(*fptr, "%d", &(temp->coef)); //input coef and exponenter
fscanf(*fptr, "%d", &(temp->exponent));
temp->next->next = NULL; //link last data to end empty node
}
term_count--;
}
fscanf(*fptr, "%d", &term_count); //store line content(ie term count to var)
pnode *temp2 = *pptr2; //traverse list
while(term_count > 0){
while(temp2->next != NULL){
temp2 = temp2->next;
}
if(temp2->next == NULL){
temp2->next = (pnode *)malloc(sizeof (pnode));
fscanf(*fptr, "%d", &(temp2->coef));
fscanf(*fptr, "%d", &(temp2->exponent));
temp->next->next = NULL;
}
term_count--;
}
}
case_count--;
}
}
The output goes like this:
Code:
5x^12 + 2x^9 + 4x^7 + 6x^6 + 1x^3 + 0
+ 7x^8 + 2x^7 + 8x^6 + 6x^4 + 2x^2 + 3x + 3x^1 + 40 + 0