试题描述
用链表实现两个二元二次多项式相乘。
输入
输入的数依次为:x,y,xy,x^2,y^2的系数。
输出
输出的数依次为:x,y,xy,x^2,y^2的系数。
样例输入
1 1 0 0 0
1 1 0 0 0
样例输出
0 0 2 1 1
语言
C
OJ提交结果
KLP平台编译运行通过,答案正确。
源代码
#include<stdio.h>
#include<stdlib.h>
typedef struct node{
int data;
struct node *next;
}Node, *Link;
void createLinklist(Link head)
{
int c,i;
Link p,q;
q = head;
for(i = 1; i <= 5; i ++)
{
p = (Link)malloc(sizeof(Node));
scanf("%d",&c);
p->data = c;
q->next = p;
p->next = NULL;
q = p;
}
q->next = NULL;
}
void mul(Link s1,Link s2,Link l)
{
int i = 4, n;
Link p, q, ms, mg;
p = s1->next;
q = s2->next;
mg = l;
if(p->data != 0 || q->data != 0)
{
ms = (Link)malloc(sizeof(Node));
ms->data = 0;
mg->next = ms;
ms->next = NULL;
mg = ms;
ms = (Link)malloc(sizeof(Node));
ms->data = 0;
mg->next = ms;
ms->next = NULL;
mg = ms;
ms = (Link)malloc(sizeof(Node));
ms->data = p->data * (q->next)->data + (p->next)->data * q->data;
mg->next = ms;
ms->next = NULL;
mg = ms;
ms = (Link)malloc(sizeof(Node));
ms->data = p->data * q->data;
mg->next = ms;
ms->next = NULL;
mg = ms;
ms = (Link)malloc(sizeof(Node));
ms->data = (p->next)->data * (q->next)->data;
mg->next = ms;
ms->next = NULL;
mg = ms;
}
else
{
for(n = 0; n < 4; n ++)
{
ms = (Link)malloc(sizeof(Node));
ms->data = 0;
mg->next = ms;
ms->next = NULL;
mg = ms;
}
}
}
void show(Link head){
Link p;
p = (Link)malloc(sizeof(Node));
p = head->next;
while(p->next != NULL){
printf("%d ",p->data);
p = p->next;
}
printf("%d",p->data);
}
int main()
{
int n;
Link num1;
Link num2;
Link List;
List = (Link)malloc(sizeof(Node));
List->next = NULL;
num1 = (Link)malloc(sizeof(Node));
num1->next = NULL;
num2 = (Link)malloc(sizeof(Node));
num2->next = NULL;
createLinklist(num1);
createLinklist(num2);
mul(num1,num2,List);
show(List);
return 0;
}