您的位置:首页 > 理论基础 > 数据结构算法

数据结构的应用——一元N次多项式的加法

2011-03-23 15:19 246 查看


采用ArrayList来实现多项式,为免要求输入时按升幂输入,可以调用Collections的sort方法。

建立每个项的类PolyItem,实现Comparable接口以便ArrayList的排序,代码如下:

/**
* 多项式的项,并实现了项的大小比较
* @author Bao Yiming
*/
class PolyItem implements Comparable<PolyItem> {
Integer coef; // 多项式某一项的系数。
Integer degree; // 多项式某一项的指数。
public PolyItem(Integer coef, Integer degree) {
this.coef = coef;
this.degree = degree;
}
/**
* 比较两项的大小,返回其指数的比较结果。
* @param o 要与当前项比较的项。
* @return
*/
public int compareTo(PolyItem o) {
return degree.compareTo(o.degree);
}
@Override
public String toString() {
if (degree != 0) {
return (coef + "X^" + degree);
} else {
return "" + coef;
}
}
}


具体的多项式类及其加法的实现如下:

package ds.linerlist;
import java.util.*;
/**
* 用ArrayList实现稀疏多项式及其运算
* @author <a href="mailto:bao.yiming@live.cn" mce_href="mailto:bao.yiming@live.cn">Bao Yiming</a>
*/
class Polynomial {
ArrayList<PolyItem> poly = new ArrayList<PolyItem>();
public Polynomial(ArrayList<PolyItem> poly) {
this.poly = poly;
Collections.sort(poly);
}
/**
* 多项式的加法
* @param p 要加的多项式
*/
public void add(Polynomial p) {
int indexA = 0; // 当前多项式A的索引。
int indexB = 0; // 要加上去的多项式B的索引。
ArrayList<PolyItem> polyB = p.poly; // 取得多项式B的内容数组。
/*
* 从多项式的第一项开始判断
*/
while (indexA < poly.size() && indexB < polyB.size()) {
Integer degreeA = poly.get(indexA).degree; // 获取多项式A当前项的幂。
Integer degreeB = polyB.get(indexB).degree; // 获取多项式B当前项的幂。
/*
* 如果A当前项的幂小于B当前项的幂,则将A当前项的索引后移一位。
* 如果A当前项的幂大于B当前项的幂,则将B当前项插入到A中。
* 如果A当前项的幂大于B当前项的幂,则将A,B的系数相加后覆盖A的内容。
*/
if (degreeA < degreeB) {
++indexA;
} else if (degreeA > degreeB) {
poly.add(indexA, polyB.remove(indexB));
} else {
Integer coefA = poly.get(indexA).coef; // 获取多项式A当前项的系数。
Integer coefB = polyB.get(indexB).coef; // 获取多项式B当前项的系数。
/**
* 当幂相等时,判断系数和是否为0,为0时删除该项。
*/
if ((coefA + coefB) != 0) {
PolyItem res = new PolyItem((coefA + coefB), degreeA);
poly.set(indexA, res);
polyB.remove(indexB);
++indexA;
} else {
poly.remove(indexA);
polyB.remove(indexB);
}
}
}
/*
* 如果多项式B中还有项,则全部添加到多项式A中。
*/
if (!polyB.isEmpty()) {
poly.addAll(indexB, polyB);
}
}
@Override
public String toString() {
StringBuilder str = new StringBuilder("");
for (PolyItem item : poly) {
str.append(item).append("+");
}
return (str.deleteCharAt(str.lastIndexOf("+"))).toString();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐