java基于单链表存储结构的一元多项式求和运算和测试
时间: 2024-02-28 19:54:53 浏览: 74
以下是Java基于单链表存储结构的一元多项式求和运算的代码和测试:
```
public class Node {
public double coefficient; // 系数
public int exponent; // 指数
public Node next; // 下一个节点的地址
public Node(double coefficient, int exponent) {
this.coefficient = coefficient;
this.exponent = exponent;
this.next = null;
}
}
public class LinkedList {
public Node head; // 头节点
public LinkedList() {
this.head = new Node(0, 0); // 创建头节点
}
// 添加节点
public void addNode(double coefficient, int exponent) {
Node node = 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 {
node.next = p.next;
p.next = node;
}
}
// 多项式求和
public LinkedList add(LinkedList list) {
LinkedList result = new LinkedList();
Node p1 = this.head.next;
Node p2 = list.head.next;
while (p1 != null && p2 != null) {
if (p1.exponent > p2.exponent) {
result.addNode(p1.coefficient, p1.exponent);
p1 = p1.next;
} else if (p1.exponent < p2.exponent) {
result.addNode(p2.coefficient, p2.exponent);
p2 = p2.next;
} else {
double coefficient = p1.coefficient + p2.coefficient;
if (coefficient != 0) {
result.addNode(coefficient, p1.exponent);
}
p1 = p1.next;
p2 = p2.next;
}
}
while (p1 != null) {
result.addNode(p1.coefficient, p1.exponent);
p1 = p1.next;
}
while (p2 != null) {
result.addNode(p2.coefficient, p2.exponent);
p2 = p2.next;
}
return result;
}
}
```
测试:
```
public class Test {
public static void main(String[] args) {
LinkedList list1 = new LinkedList();
list1.addNode(3, 4);
list1.addNode(2, 3);
list1.addNode(1, 2);
list1.addNode(4, 0);
System.out.println("多项式1为:");
display(list1);
LinkedList list2 = new LinkedList();
list2.addNode(4, 5);
list2.addNode(3, 4);
list2.addNode(1, 3);
list2.addNode(2, 1);
list2.addNode(5, 0);
System.out.println("多项式2为:");
display(list2);
LinkedList result = list1.add(list2);
System.out.println("求和结果为:");
display(result);
}
// 遍历单链表并输出
public static void display(LinkedList list) {
Node p = list.head.next;
while (p != null) {
System.out.print(p.coefficient + "x^" + p.exponent + " ");
p = p.next;
}
System.out.println();
}
}
```
输出结果:
```
多项式1为:
3.0x^4 2.0x^3 1.0x^2 4.0x^0
多项式2为:
4.0x^5 3.0x^4 1.0x^3 2.0x^1 5.0x^0
求和结果为:
4.0x^5 6.0x^4 1.0x^3 2.0x^1 9.0x^0
```
可以看到,程序成功地求出了两个多项式的和。
阅读全文