多项式按指数递减排列。
//链表节点
class Point {
int ceof; //系数
int expon; //指数
Point next;
}
public class Main {
public static void main(String[] args) {
polynomial();
}
/**
* 输入两个一元多项式(系数,指数)
* 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
*
*/
public static void polynomial() {
Scanner sc = new Scanner(System.in);
//构建链表1
int n1 = sc.nextInt();
Point head1 = new Point();
Point t1 = head1;
for(int i = 0; i < n1; i++) {
Point node = new Point();
node.ceof = sc.nextInt();
node.expon = sc.nextInt();
t1.next = node;
t1 = t1.next;
}
//构建链表2
int n2 = sc.nextInt();
Point head2 = new Point();
Point t2 = head2;
for(int i = 0; i < n2; i++) {
Point node = new Point();
node.ceof = sc.nextInt();
node.expon = sc.nextInt();
t2.next = node;
t2 = t2.next;
}
//相乘
printList(mul(head1,head2).next);
//相加
printList(add(head1,head2).next);
}
//两个多项式相乘
public static Point mul(Point head1, Point head2) {
Point p1 = null;
if(head2.next != null)
p1 = mulOne(head1,head2.next);
Point t2 = head2.next.next;
while(t2 != null) {
Point p2 = mulOne(head1,t2);
t2 = t2.next;
p1 = add(p1,p2);
}
return p1;
}
//一个多项式与一个节点相乘
public static Point mulOne(Point head1, Point point) {
Point t1 = head1.next;
Point newHead = new Point();
Point p1 = newHead;
while(t1 != null) {
Point p = new Point();
p.ceof = t1.ceof * point.ceof; //系数相乘
p.expon = t1.expon + point.expon; //指数相加
t1 = t1.next;
p1.next = p;
p1 = p1.next;
}
return newHead;
}
//两个多项式相加
public static Point add(Point head1, Point head2) {
Point pre = head1;
Point t1 = head1.next;
Point t2 = head2.next;
//将t2链表加到t1链表上
while(t1 != null && t2 != null) {
if(t1.expon > t2.expon) {
pre = t1;
t1 = t1.next;
continue;
}
if(t1.expon < t2.expon) {
Point p2 = t2.next;
t2.next = t1;
pre.next = t2;
pre = pre.next;
t2 = p2;
continue;
}
if(t1.expon == t2.expon) {
t1.ceof = t1.ceof + t2.ceof;
if(t1.expon == 0) { //删除该节点
Point p1 = t1.next;
pre.next = p1;
t1 = p1;
pre = t2;
t2 = t2.next;
}else {
t1 = t1.next;
t2 = t2.next;
}
}
}
//将t2链表多余的加到t1
while(t2 != null) {
pre.next = t2;
t2 = t2.next;
pre = pre.next;
}
//printList(head1.next);
return head1;
}
//打印多项式
public static void printList(Point p) {
while(p != null) {
System.out.print(p.ceof+" "+p.expon+" ");
p = p.next;
}
System.out.println();
}
}
运行结果:
两个多项式相乘的方法:
1、将其中一个链表的每一个节点乘与另一个链表,然后相加起来。
2、将其中一个链表的每一个节点乘与另一个链表,然后插入一个新的链表,寻找插入的位置,按指数递减的方式。
这里采用的是方法1。