一元多项式的乘法和加法
Posted dyq19
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了一元多项式的乘法和加法相关的知识,希望对你有一定的参考价值。
//一元多项式的乘法和加法
import java.util.*;
class Node{
int index;
int coef;
Node next = null;
public Node(int coef, int index) {
this.index = index;
this.coef = coef;
}
}
class Link{
Node head = null;
Node tmp = null;
public void addnode(int coef,int index) {
Node n = new Node(coef,index);
if(head == null) {
head = n;
tmp = head;
return;
}
tmp.next = n;
while(tmp.next != null) {
tmp = tmp.next;
}
}
public Link pluslink(Link a,Link b) {
Link c = new Link();
a.tmp = a.head;
b.tmp = b.head;
while(a.tmp != null && b.tmp !=null) {
if(a.tmp.index == b.tmp.index) {
if(a.tmp.coef+b.tmp.coef!=0) {
c.addnode(a.tmp.coef+b.tmp.coef,a.tmp.index);}
a.tmp = a.tmp.next;
b.tmp = b.tmp.next;
}
else if(a.tmp.index > b.tmp.index) {
c.addnode( a.tmp.coef,a.tmp.index);
a.tmp = a.tmp.next;
}
else if(a.tmp.index < b.tmp.index) {
c.addnode(b.tmp.coef,b.tmp.index);
b.tmp = b.tmp.next;
}
}
if(a.tmp == null) {
while(b.tmp != null) {
c.addnode(b.tmp.coef,b.tmp.index);
b.tmp = b.tmp.next;
}
}
else if(b.tmp == null) {
while(a.tmp != null) {
c.addnode(a.tmp.coef,a.tmp.index);
a.tmp = a.tmp.next;
}
}
return c;
}
public Link multiplelink(Link a,Link b) {
a.tmp = a.head;
b.tmp = b.head;
Link m = new Link();
while(a.tmp != null) {
Link l = new Link();
while(b.tmp !=null) {
l.addnode(a.tmp.coef*b.tmp.coef, a.tmp.index+b.tmp.index);
b.tmp = b.tmp.next;
}
m=pluslink(m, l);
a.tmp = a.tmp.next;
b.tmp = b.head;
}
return m;
}
public void printlink(Link a) {
a.tmp = a.head;
int n = 0;
if(a.tmp == null)
{System.out.print("0 0");}
else{
while(a.tmp != null) {
if(a.tmp.coef != 0) {
System.out.print(a.tmp.coef +" "+a.tmp.index);
n++;
a.tmp = a.tmp.next;
{while(a.tmp != null) {
if(a.tmp.coef != 0) {
System.out.print(" "+a.tmp.coef +" "+a.tmp.index);
n++;
}
a.tmp = a.tmp.next;
}break;
}
}
else {a.head = a.tmp;}
a.tmp = a.tmp.next;
}
if(n==0) {
System.out.print("0 0");
}
}
}
}
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
Link s1 = new Link();
int N1=in.nextInt();
for(int n = N1; n>0; n--) {
s1.addnode(in.nextInt(), in.nextInt());
}
Link s2 = new Link();
int N2=in.nextInt();
for(int n =N2; n>0; n--) {
s2.addnode(in.nextInt(), in.nextInt());
}
Link s3 = new Link();
if(N1>=N2){
s3.printlink(s3.multiplelink(s2, s1));
}
else {
s3.printlink(s3.multiplelink(s1, s2));
}
System.out.println();
s3.printlink(s3.pluslink(s1, s2));
in.close();
}
}
1.判断是否是零多项式可以在加法时判断,我是在输出时判断的,应该在加法处判断比较简单;
2.输入零多项式和常数多项式中的零多项式就是不输入(。。)而不是输入0 0。
以上是关于一元多项式的乘法和加法的主要内容,如果未能解决你的问题,请参考以下文章