设一个一元多项式采用带头结点的单链表存储,所有结点
按照升幂方式链接。设计一个算法,求两个多项式 A 和 B 的乘积,结果多项式 C
存放在新辟的空间中。
(这个完全就是浙大慕课上讲的一模一样因为我认真听了,原来自己写的实在不想调试了hhh)
#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
#define Elemtype int
typedef struct Pnode
{
int coef; //系数
int expn;//指数
struct Pnode* next;
}Pnode, *Polyn;
void Attacha(int c, int e, Polyn* head)
{
Polyn P;
P = (Polyn)malloc(sizeof(Pnode));
P->coef = c;
P->expn = e;
P->next = NULL;
(*head)->next = P;
*head = P;
}
Polyn Mult(Polyn p1, Polyn p2)
{
if (!p1 || !p2)
return NULL;
int c, e;
Polyn p, rear, t1,t2,t;//头
t1 = p1, t2 = p2;
p = (Polyn)malloc(sizeof(Pnode)); //新建的链表的头结点
p->next = NULL;
rear = p;
while (t2) //先用p1的第一项乘p2的每一项
{
Attacha(t1->coef * t2->coef, t1->expn + t2->expn, &rear);
t2 = t2->next;
}
t1 = t1->next;
while (t1)
{
t2 = p2; rear = p;
while (t2)
{
c = t1->coef * t2->coef;
e = t1->expn + t2->expn;
while (rear->next && rear->next->expn < e) //找插入的位置,找指数即可
rear = rear->next;
if (rear->next && rear->next->expn == e) //分析相等的情况
{
if (rear->next->coef + c) //系数相等则直接相加
rear->next->coef += c;
else { //若系数和等于0,则跳过这个点,即删除
t = rear->next;
rear->next = t->next;
free(t);
}
}
else { //插入操作
t= (Polyn)malloc(sizeof(Pnode)); //重新申请一个结点,把当前项的值赋予
t->coef = c; t->expn = e;
t->next = rear->next; //插入排好序的位置
rear->next = t; rear = rear->next;
}
t2 = t2->next;
}
t1 = t1->next;
}
t2 = p; p = p->next; free(t2); //返回相乘后的链表操作
return p;
}
// 读入链表
Polyn CreatDnode()
{
int coef, expn, len;
printf("请输入len的值:");
scanf_s("%d", &len);
Polyn p,rear,q;//头
p = (Pnode*)malloc(sizeof(Pnode)); //建的头结点
p->next = NULL;
rear = p;
printf("请开始输入:\n");
while(len--)
{
scanf_s("%d %d", &coef, &expn);//存放数据与指数
Attacha(coef, expn, &rear); //将当前项插入多项式尾部
}
q = p; p = p->next; free(q); //删除临时生成的头结点
return p;
}
void PrintList(Polyn p)
{
printf("请输出结果:");
printf("\n");
int flag = 0;
if (!p) {
printf("0 0\n");
return;
}
while (p)
{
if (!flag) {
flag = 1;
}else
printf(" ");
printf("%d %d", p->coef, p->expn);
p = p->next;
}
printf("\n");
return;
}
int main()
{
Polyn p1,p2,p=NULL;
p1 = CreatDnode();
p2= CreatDnode();
p = Mult(p1, p2);
PrintList(p);
return 0;
}