一元多项式求和

复习一下链表

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106

#include<stdio.h>
#include<stdlib.h>
typedef struct lnode{
int expn,coef;
struct lnode* next;
}lnode ,* lptr;
//lptr是一个指向某个结点的指针
lptr creat(){
//一元多项式链表的创建
lptr head,end,s=NULL;
head=(lptr)malloc(sizeof(lnode));
int expn,coef,count;
head->next=NULL;
end=head;
//初始情况下,head和end指向同一个初始结点
printf("请输入多项式的项数count=:");
scanf("%d",&count);
for(int i=0;i<count;i++){
printf("请输入第%d项的系数和指数:",i+1);
scanf("%d%d",&coef,&expn);
s=(lptr)malloc(sizeof(lnode));
s->coef=coef;
s->expn=expn;
s->next=NULL;
//将新创建的节点插到尾部
end->next=s;
end=s;
}
return head;
}
void travel(lptr head){
//遍历链表
lptr p=head->next;
while(p!=NULL){
if(p->next!=NULL){
if(p->coef!=1){
printf("%dx∧%d+",p->coef,p->expn);
p=p->next;
}
else {
printf("x∧%d+",p->expn);
p=p->next;
}
}
else{
if(p->coef!=1){
printf("%dx∧%d",p->coef,p->expn);
p=p->next;
}
else
{
printf("x∧%d",p->expn);
p=p->next;
}
}
}
printf("n");
}
lptr add(lptr head_a,lptr head_b){
//多项式相加
lptr sum_head=(lptr)malloc(sizeof(lnode));
sum_head->next=NULL;
lptr sum_end=sum_head;
lptr p_a=head_a->next;
lptr p_b=head_b->next;
while(p_a&&p_b){
if(p_a->expn<p_b->expn){
sum_end->next=p_a;
sum_end=p_a;
p_a=p_a->next;
}
else if(p_a->expn>p_b->expn){
sum_end->next=p_b;
sum_end=p_b;
p_b=p_b->next;
}
else{
if(0!=p_a->coef+p_b->coef){
//指数相同的话就先把和赋给a
p_a->coef=p_a->coef+p_b->coef;
sum_end->next=p_a;
sum_end=p_a;
}
p_a=p_a->next;
p_b=p_b->next;
}
}
//插入剩余项
if(p_a!=NULL){
sum_end->next=p_a;
}
if(p_b!=NULL){
sum_end->next=p_b;
}
return sum_head;
}
int main(){
lptr a=creat();
lptr b=creat();
travel(a);
travel(b);
lptr sum=add(a,b);
travel(sum);
return 0;
}