【问题描述】
编写一个程序实现两个一元多项式相乘。
【输入形式】
首先输入第一个多项式中系数不为0的项的系数和指数,以一个空格分隔。且该多项式中各项的系数均为0或正整数,系数和最高幂次不会超过int类型的表示范围。对于多项式 anxn +a n-1 x n-1 + … + a1x1 + a0x0 的输入方法如下:
an n a n-1 n-1 … a1 1 a0 0
即相邻两个整数分别表示表达式中一项的系数和指数。在输入中只出现系数不为0的项。最后一项的指数后没有空格,只有一个回车换行符。
按照上述方式再输入第二个多项式。
【输出形式】
将运算结果输出到屏幕。将系数不为0的项按指数从高到低的顺序输出,每次输出其系数和指数,均以一个空格分隔,最后一项的指数后也可以有一个空格。
【样例输入】
10 80000 2 6000 7 300 5 10 18 0
3 6000 5 20 8 10 6 0
【样例输出】
30 86000 50 80020 80 80010 60 80000 6 12000 21 6300 10 6020 31 6010 66 6000 35 320 56 310 42 300 25 30 130 20 174 10 108 0
【样例说明】
提示:利用链表存储多项式的系数和指数。
方法一
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
struct node
{
long long num;
long long index;
struct node *next;
};
typedef struct node *Nodeptr;
typedef struct node Node;
Nodeptr insertNode(Nodeptr head, long long num, long long index)
{
Nodeptr p = head, q = NULL, r = NULL;
r = (Nodeptr)malloc(sizeof(Node));
r->num = num;
r->index = index;
r->next = NULL;
if (head == NULL)
return r;
for (p = head; p != NULL && p->index > index; q = p, p = p->next)
;
if (p != NULL && p->index == index)
{
p->num += num;
}
else if (p == head)
{
r->next = p;
return r;
}
else
{
q->next = r;
r->next = p;
}
return head;
}
int printNode(Nodeptr head)
{
if