Hi all.I wrote a program to impelement the add operation of polynomial with list.For example,I wanna do the add operation on
x^2+3x^4+6x^5 AND x-5x^4+x^5-4x^6
I creat two list,the input should be:
1 2
3 4
6 5
EOF
1 1
-5 4
1 5
-4 6
EOF
my question is at Line 137~140.I haven't initialize the local variable P,however,It has a value!Why?I think it's the key to fix my program.
Code:
#include<stdio.h>
#include<malloc.h>
typedef struct Polynomial{
int coe;
int order;
struct Polynomial *next;
}Poly;
int creat_list(Poly** head);
void print_list(Poly *head);
void insert_node(Poly *head,Poly *py);
void del_node(Poly *head,Poly *py);
void add_poly(Poly *h1,Poly *h2);
void print_result(Poly *head);
int main(){
Poly *head1,*head2;
creat_list(&head1);
//printf("---------------------\n");
// print_list(head1);
creat_list(&head2);
//printf("---------------------\n");
// print_list(head2);
add_poly(head1,head2);
printf("---------------------\n");
print_result(head1);
return 0;
}
int creat_list(Poly** head){
int coe,order;
*head = (Poly*)malloc(sizeof(Poly));
if(*head == NULL) return 0;
Poly *p = *head;
(*head)->next = NULL;
printf("input the coe and order:\n");
while(scanf("%d %d",&coe,&order) == 2){
//The algorithm will be right only if
//you enter the unique order in order.
Poly *newnode = (Poly *)malloc(sizeof(Poly));
newnode->coe = coe;
newnode->order = order;
newnode->next = NULL;
p->next = newnode;
p = newnode;
printf("input the coe and order:\n");
}
return 1;
}
void insert_node(Poly *head,Poly *py){
int flag = 0;
Poly *pre = head->next,*aft = head;
while(pre){
if(pre->order < py->order){
aft = pre;
pre = pre->next;
continue;
}
else if(pre->order > py->order){
aft->next = py;
py->next = pre;
flag = 1;
break;
}
else{
if(pre->coe+py->coe){
pre->coe += py->coe;
flag = 1;
break;
}
else{
Poly p = *py;
del_node(head,&p);
flag = 1;
break;
}
}
}
if(!flag){
aft->next = py;
py->next = NULL;
}
}
void del_node(Poly *head,Poly *py){
Poly *pre = head->next,*aft = head;
while(pre){
if(pre->coe == py->coe &&\
pre->order == py->order){
aft->next = pre->next;
//break;
//ignore break in case of more than one matched
}
aft = pre;
pre = pre->next;
}
}
void add_poly(Poly *h1,Poly *h2){
Poly *pre = h1->next,*aft = h1;
Poly *p2 = h2->next;
while(p2 && pre){
if(pre->order < p2->order){
aft = pre;pre = pre->next;
continue;
}
else if(pre->order > p2->order){
Poly p = *p2;
insert_node(h1,&p);
p2 = p2->next;
continue;
}
else{
if((pre->coe+p2->coe) == 0){
aft = pre;pre = pre->next;
del_node(h1,aft);
p2 = p2->next;
}
else{
pre->coe += p2->coe;
aft = pre;pre = pre->next;
p2 = p2->next;
}
}
}
if(pre == NULL){
while(p2){
print_list(h1);
Poly p;//p = *p2;
printf("&&%d %d\n",p.coe,p.order);
print_list(h1);
insert_node(h1,&p);
p2 = p2->next;
}
}
}
void print_result(Poly *head){
Poly *p = head->next;
while(p){
printf("%+dx^%d",p->coe,p->order);
p = p->next;
}
printf("\n");
}
void print_list(Poly *head){
Poly *p = head->next;
while(p != NULL){
printf("%d %d\n",p->coe,p->order);
p = p->next;
}
}