# PTA一元多项式的乘法与加法运算 测试点

0

``````#include<stdio.h>
#include<stdlib.h>
#include<math.h>

typedef struct Node *PtrToNode;
struct Node{
int xishu;
int zhishu;
PtrToNode Next;
};
typedef PtrToNode List;

List MUL(List, List);
void Print(List);
void Free(List);

int main()
{
List L1, L2, L3, L4;
L3 = MUL(L1, L2);

Print(L3);
Print(L4);

Free(L1);
Free(L2);
Free(L3);
Free(L4);

return 0;
}

{
int i, N;
List L = (List)malloc(sizeof(struct Node));
PtrToNode LN = L;

scanf("%d", &N);
for( i=1; i<=N; ++i ){
PtrToNode P = (PtrToNode)malloc(sizeof(struct Node));
scanf("%d %d", &P->xishu, &P->zhishu);
LN->Next = P;
LN = LN->Next;
}
LN->Next = NULL;

return L;
}
List MUL(List L3, List L4)
{

List L1, L2, L, LN;
L = (List)malloc(sizeof(struct Node));  //乘到一起的链表
L->Next = NULL;

for( L2=L4->Next; L2; L2=L2->Next ){      //两个链表中的每一个节点都互相相乘
for( L1=L3->Next; L1; L1=L1->Next ){
PtrToNode P = (PtrToNode)malloc(sizeof(struct Node));
P->xishu = L1->xishu * L2->xishu;
P->zhishu = L2->zhishu + L1->zhishu;
P->Next = NULL;
for( LN=L; LN->Next; LN=LN->Next ){     //与新链表中已有的节点比较
if( LN->Next->zhishu == P->zhishu ){
LN->Next->xishu += P->xishu;
if( LN->Next->xishu == 0 ){     //若指数相等，系数相加为0，去掉节点
P->Next = LN->Next;     //由于要新建一个变量比较麻烦，可以直接接到P后面，（可以吗）
LN->Next = LN->Next->Next;
free(P->Next);      //
}
free(P);
break;
}
if( LN->Next->zhishu < P->zhishu ){ //若链表中指数小于，节点指数。移位
P->Next = LN->Next;
LN->Next = P;
break;
}
}
if( !LN->Next ) LN->Next = P;       //若遍历一遍链表都比此节点大，则此节点加到链表最后
}
}

return L;
}
{

List L1 = L3, L2 = L4, LN;
List L = (List)malloc(sizeof(struct Node));
L->Next = NULL;
LN = L;
while( L1->Next && L2->Next ){      //有头结点
PtrToNode P = (PtrToNode)malloc(sizeof(struct Node));
if( L1->Next->zhishu == L2->Next->zhishu ){
if( L1->Next->xishu+L2->Next->xishu ){      //指数相等，系数相加不为0，
P->xishu = L1->Next->xishu+L2->Next->xishu;
P->zhishu = L1->Next->zhishu;
L1 = L1->Next;
L2 = L2->Next;
}else{      //系数相加为0
L1 = L1->Next;
L2 = L2->Next;
free(P);
continue;
}
}else if( L1->Next->zhishu > L2->Next->zhishu ){
P->xishu = L1->Next->xishu;
P->zhishu = L1->Next->zhishu;
L1 = L1->Next;
}else {
P->xishu = L2->Next->xishu;
P->zhishu = L2->Next->zhishu;
L2 = L2->Next;
}
LN->Next = P;
LN = LN->Next;
}
while( L1->Next ){
PtrToNode P = (PtrToNode)malloc(sizeof(struct Node));
P->xishu = L1->Next->xishu;
P->zhishu = L1->Next->zhishu;
L1 = L1->Next;
LN->Next = P;
LN = LN->Next;
}
while( L2->Next ){
PtrToNode P = (PtrToNode)malloc(sizeof(struct Node));
P->xishu = L2->Next->xishu;
P->zhishu = L2->Next->zhishu;
L2 = L2->Next;
LN->Next = P;
LN = LN->Next;
}
LN->Next = NULL;
return L;
}
void Print(List L)
{
List LN = L;
if( !L->Next ) printf("0 0");
for( LN=LN->Next; LN; LN=LN->Next ){
printf("%d %d", LN->xishu, LN->zhishu);
if( LN->Next ) printf(" ");
}
printf("\n");
}
void Free(List L)
{
List LN;
for( LN=L->Next; LN; LN=LN->Next ){
free(L);    //
L = LN;
}
free(L);
}``````

り罐罐。 | 初学一级 | 园豆：46

您需要登录以后才能回答，未注册用户请先注册