本题求两个有序多项式的求和,输入的多项式有两项:系数和指数。
多项式采用链式存储,并按指数从小到大排列。
输出时也按指数从小到大的顺序输出。
(数据输入时按指数从小到大顺序输入,输入0 0时表示结束。构造部分已完成,不需自己编写)
为简化链表构造,默认构造链表为加监督元单链表。
函数接口定义:
ptr add(ptr ha,ptr hb);
add是两个有序链表ha,hb进行相加运算,构成一个新的链表返回,原链表ha,hb保留。
裁判测试程序样例:
#include <stdio.h> #include <malloc.h> typedef struct node { float ceof; int exp; struct node *next; }node,*ptr; ptr creat();//表尾插入法构造链表,在此不表 ptr add(ptr ha,ptr hb); void output(ptr h) { ptr p; p=h->next; while(p!=NULL) { printf("%+.1fx^%d",p->ceof,p->exp); p=p->next; } printf("\n"); } int main() { ptr h1,h2,h3; h1=creat(); h2=creat(); h3=add(h1,h2); output(h1); output(h2); output(h3); return 0; } /* 请在这里填写答案 */
输入样例:
-19 0
21 2
90.2 5
100 10
18 92
0 0
19 0
-21 2
65 4
-8 5
43.6 14
0 0
输出样例:
-19.0x^0+21.0x^2+90.2x^5+100.0x^10+18.0x^92
+19.0x^0-21.0x^2+65.0x^4-8.0x^5+43.6x^14
+65.0x^4+82.2x^5+100.0x^10+43.6x^14+18.0x^92
具体解法 注意是带头结点
其实不难根据指数级,通过不同情况的判断完成插入尾结点 更新尾结点
ps.有查重 请勿照抄 谢谢配合!
ptr add(ptr ha, ptr hb)
{
ptr WWWW,t,p,h1,h2;
WWWW=t=p=(ptr)malloc(sizeof(node));
h1=ha->next;
h2=hb->next;
while(h1&&h2)
{
if (h1->exp<h2->exp)
{
p=(ptr)malloc(sizeof(node));
p=h1;
h1=h1->next;
t->next=p;
t=p;
}
else if(h1->exp==h2->exp)
{
if(h1->ceof+h2->ceof==0.0)
{
h1=h1->next;
h2=h2->next;
}
else
{
p=(ptr)malloc(sizeof(node));
p->exp=h2->exp;
p->ceof=h1->ceof+h2->ceof;
h1=h1->next;
h2=h2->next;
t->next=p;
t=p;
}
}
else
{
p=(ptr)malloc(sizeof(node));
p=h2;
t->next=p;
t=p;
h2=h2->next;
}
}
while (h1!= NULL)
{
p=(ptr)malloc(sizeof(node));
p=h1;
h1=h1->next;
t->next = p;
t= p;
}
while (h2!=NULL)
{
p=(ptr)malloc(sizeof(node));
p=h2;
h2=h2->next;
t->next =p;
t=p;
}
t->next=NULL;
return WWWW;
}