Java用两个线性链表分别存储两个一元多项式,试实现两个多项式的加法/减法运算。 [基本要求] 一元多项式用链式存储结构实现存储; 注意: 1、多项式表的链表定义方法 2、注意临界状态的处理。的源代码
时间: 2023-06-12 08:03:41 浏览: 135
以下是Java实现两个多项式的加法和减法的代码:
```
class Node {
float coefficient; // 系数
int exponent; // 指数
Node next; // 指向下一个节点的指针
public Node(float coefficient, int exponent) {
this.coefficient = coefficient;
this.exponent = exponent;
next = null;
}
}
class Polynomial {
Node head; // 链表头
public Polynomial() {
head = new Node(0, -1); // 头节点不存储任何数据
}
// 添加一个节点
public void addNode(float coefficient, int exponent) {
Node newNode = new Node(coefficient, exponent);
Node p = head;
while (p.next != null && p.next.exponent > exponent) {
p = p.next;
}
if (p.next != null && p.next.exponent == exponent) {
p.next.coefficient += coefficient;
} else {
newNode.next = p.next;
p.next = newNode;
}
}
// 打印多项式
public void print() {
Node p = head.next;
while (p != null) {
System.out.print(p.coefficient + "x^" + p.exponent + " + ");
p = p.next;
}
System.out.println();
}
}
public class Main {
// 多项式加法
public static Polynomial add(Polynomial p1, Polynomial p2) {
Polynomial result = new Polynomial();
Node p = p1.head.next, q = p2.head.next;
while (p != null && q != null) {
if (p.exponent > q.exponent) {
result.addNode(p.coefficient, p.exponent);
p = p.next;
} else if (p.exponent < q.exponent) {
result.addNode(q.coefficient, q.exponent);
q = q.next;
} else {
float sum = p.coefficient + q.coefficient;
if (sum != 0) {
result.addNode(sum, p.exponent);
}
p = p.next;
q = q.next;
}
}
while (p != null) {
result.addNode(p.coefficient, p.exponent);
p = p.next;
}
while (q != null) {
result.addNode(q.coefficient, q.exponent);
q = q.next;
}
return result;
}
// 多项式减法(实际上是加上一个系数为负数的多项式)
public static Polynomial subtract(Polynomial p1, Polynomial p2) {
Polynomial negativeP2 = new Polynomial();
Node p = p2.head.next;
while (p != null) {
negativeP2.addNode(-p.coefficient, p.exponent);
p = p.next;
}
return add(p1, negativeP2);
}
public static void main(String[] args) {
Polynomial p1 = new Polynomial();
p1.addNode(3, 3);
p1.addNode(4, 2);
p1.addNode(2, 1);
p1.addNode(1, 0);
System.out.print("p1 = ");
p1.print();
Polynomial p2 = new Polynomial();
p2.addNode(5, 4);
p2.addNode(-3, 3);
p2.addNode(2, 2);
p2.addNode(1, 0);
System.out.print("p2 = ");
p2.print();
Polynomial p3 = add(p1, p2);
System.out.print("p1 + p2 = ");
p3.print();
Polynomial p4 = subtract(p1, p2);
System.out.print("p1 - p2 = ");
p4.print();
}
}
```
上述代码中,Node类表示链表的节点,Polynomial类表示一个多项式,head指向多项式的头节点。Polynomial类中的addNode方法用于添加一个节点,print方法用于打印多项式。Main类中的add方法和subtract方法分别实现了多项式的加法和减法。程序中还有一个测试用例,可以用来测试实现的正确性。
阅读全文