用两个线性链表分别存储两个一元多项式,试实现两个多项式的加法/减法运算。(用Java)(带文字注释)
时间: 2024-05-10 20:15:22 浏览: 100
假设我们要实现的多项式的结构体如下:
```java
class Term {
int coefficient; // 系数
int exponent; // 指数
Term next; // 下一项
}
```
我们可以用两个链表 `p1` 和 `p2` 分别存储两个多项式,每个链表中的元素是一个 `Term` 结构体。
多项式的加法运算可以分为以下几步:
1. 遍历链表 `p1` 和 `p2` ,将相同指数的项相加,得到结果链表 `result`。
2. 将 `p1` 和 `p2` 中剩余的项依次加入到 `result` 中。
多项式的减法运算与加法运算类似,只需要将相同指数的项相减即可。
下面是实现多项式加法和减法的 Java 代码:
```java
public class Polynomial {
private Term head1, head2, result;
// 链表中插入一个新的项
private void insertTerm(Term head, int coefficient, int exponent) {
Term p = head;
while (p.next != null) {
p = p.next;
}
Term newTerm = new Term();
newTerm.coefficient = coefficient;
newTerm.exponent = exponent;
newTerm.next = null;
p.next = newTerm;
}
// 把链表中的项按照指数递减顺序排序
private void sort(Term head) {
int len = getLength(head);
for (int i = 0; i < len - 1; i++) {
Term p = head.next, q = head;
for (int j = 0; j < len - i - 1; j++) {
if (p.exponent > p.next.exponent) {
q.next = p.next;
Term tmp = p.next.next;
p.next.next = p;
p.next = tmp;
}
q = p;
p = p.next;
}
}
}
// 获取链表长度
private int getLength(Term head) {
int len = 0;
Term p = head.next;
while (p != null) {
len++;
p = p.next;
}
return len;
}
// 多项式相加
public Term add(Term head1, Term head2) {
sort(head1);
sort(head2);
Term p1 = head1.next, p2 = head2.next;
result = new Term();
Term p = result;
while (p1 != null && p2 != null) {
if (p1.exponent > p2.exponent) {
p.next = p1;
p1 = p1.next;
} else if (p1.exponent < p2.exponent) {
p.next = p2;
p2 = p2.next;
} else {
int coefficient = p1.coefficient + p2.coefficient;
if (coefficient != 0) {
insertTerm(result, coefficient, p1.exponent);
}
p1 = p1.next;
p2 = p2.next;
}
p = p.next;
}
while (p1 != null) {
p.next = p1;
p1 = p1.next;
p = p.next;
}
while (p2 != null) {
p.next = p2;
p2 = p2.next;
p = p.next;
}
return result;
}
// 多项式相减
public Term subtract(Term head1, Term head2) {
sort(head1);
sort(head2);
Term p1 = head1.next, p2 = head2.next;
result = new Term();
Term p = result;
while (p1 != null && p2 != null) {
if (p1.exponent > p2.exponent) {
p.next = p1;
p1 = p1.next;
} else if (p1.exponent < p2.exponent) {
p.next = new Term();
p.next.coefficient = -p2.coefficient;
p.next.exponent = p2.exponent;
p2 = p2.next;
} else {
int coefficient = p1.coefficient - p2.coefficient;
if (coefficient != 0) {
insertTerm(result, coefficient, p1.exponent);
}
p1 = p1.next;
p2 = p2.next;
}
p = p.next;
}
while (p1 != null) {
p.next = p1;
p1 = p1.next;
p = p.next;
}
while (p2 != null) {
p.next = new Term();
p.next.coefficient = -p2.coefficient;
p.next.exponent = p2.exponent;
p2 = p2.next;
p = p.next;
}
return result;
}
}
```
阅读全文