# 一元多项式的乘法与加法运算（Java）

### 输入样例:

4 3 4 -5 2  6 1  -2 0
3 5 20  -7 4  3 1


### 输出样例:

15 24 -25 22 30 21 -10 20 -21 8 35 6 -33 5 14 4 -15 3 18 2 -6 1
5 20 -4 4 -5 2 9 1 -2 0

### 代码如下：

import java.util.*;

class X{
int xishu;
int zhishu;
X next;
public X(int xishu, int zhishu) {
super();
this.xishu = xishu;
this.zhishu = zhishu;
this.next = null;
}
}

public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n1 = sc.nextInt();
int[][] x1 = new int[n1][2];
for(int i=0;i<n1;i++) {
x1[i][0] = sc.nextInt();
x1[i][1] = sc.nextInt();
}
int n2 = sc.nextInt();
int[][] x2 = new int[n2][2];
for(int i=0;i<n2;i++) {
x2[i][0] = sc.nextInt();
x2[i][1] = sc.nextInt();
}
//计算乘法部分
X first = new X(0, 0);
for(int i=0;i<n1;i++)
for(int j=0;j<n2;j++) {
first = insert(first, x1[i][0]*x2[j][0], x1[i][1]+x2[j][1]);
}
print(first);
//计算加法部分
X second = new X(0, 0);
for(int i=0;i<n1;i++) {
second = insert(second, x1[i][0], x1[i][1]);
}
for(int i=0;i<n2;i++) {
second = insert(second, x2[i][0], x2[i][1]);
}
print(second);
}
//插入多项式方法
public static X insert(X x, int xishu, int zhishu) {
if(zhishu>x.zhishu) {
X tmp = new X(xishu, zhishu);
tmp.next = x;
x = tmp;
}
else {
X p = x;
X q = null;
while(p!=null) {
if(p.zhishu==zhishu) {
p.xishu+=xishu;
//如果系数变成0了则将那一项去掉
if(p.xishu==0) {
if(q!=null) {
q.next = p.next;
}
else {
x = x.next;
}
}
break;
}
else if(p.next!=null && p.zhishu>zhishu && p.next.zhishu<zhishu) {
X tmp = new X(xishu, zhishu);
tmp.next = p.next;
p.next = tmp;
break;
}
q = p;
p = p.next;
}
}
return x;
}
//输出方法
public static void print(X x) {
if(x==null || x.xishu==0) {
System.out.println("0 0");
}
else {
if(x.next!=null) {
while(x.next.zhishu!=0) {
System.out.print(x.xishu+" "+x.zhishu+" ");
x = x.next;
}
if(x.next.xishu==0) {
System.out.println(x.xishu+" "+x.zhishu);
}
else {
System.out.print(x.xishu+" "+x.zhishu+" ");
x = x.next;
System.out.println(x.xishu+" "+x.zhishu);
}
}
else {
System.out.println(x.xishu+" "+x.zhishu);
}
}
}
}


©️2019 CSDN 皮肤主题: 大白 设计师: CSDN官方博客