導航:首頁 > 編程語言 > java兩多項式相加

java兩多項式相加

發布時間:2023-05-25 22:02:09

『壹』 Java數據結構編程題目

自己參考下吧,希望對你有用!

//用單鏈表來實現多項式的加法,代碼如下
public class Polynomial {
private Monomial first; // 首項

// 添加單項式

public void append(Monomial monomial) {
if (monomial == null) {
// do nothing
} else if (first == null) {
first = monomial;
} else {
Monomial current = first;
while (current != null) {
// 提示:如果指數相同,則相加
if (current.index == monomial.index) {
current.coefficient += monomial.coefficient;
break;
} else if (current.next == null) { // 否則直接把此項扔到最後
current.next = monomial;
break;
}
current = current.next;
}
}
}

public void append(int c, int i) {
append(new Monomial(c, i));
}

public String toString() {//toString()方法就是把對象轉換成String類型
//比如一個Integer對象的toString方法就是把這個對象表示的整數轉化成字元串,133就成了"133"。
StringBuffer sb = new StringBuffer();
Monomial current = first;
while (current.next != null) {
sb.append("(" + current.coefficient + "x^" + current.index
+ ") + ");
current = current.next;
}
sb.append("(" + current.coefficient + "x^" + current.index + ")");
return sb.toString();
}

// 兩個多項式相加
public Polynomial add(Polynomial p2) {
Polynomial result = new Polynomial();
Monomial current = this.first;
while (current != null) {
result.append(current.coefficient, current.index); // 提示:注意這里
current = current.next;
}
current = p2.first;
while (current != null) {
result.append(current.coefficient, current.index);
current = current.next;
}
return result;
}

public static void main(String[] args) {
//構造多項式p1的每一項
Polynomial p1 = new Polynomial();
p1.append(3, 4);
p1.append(-6, 2);
p1.append(5, 1);
p1.append(-10, 0);
System.out.println("p1: " + p1);
//構造多項式p2的每一項
Polynomial p2 = new Polynomial();
p2.append(2, 5);
p2.append(-6, 2);
p2.append(5, 1);
System.out.println("p2: " + p2);
Polynomial result = p1.add(p2);
System.out.println("p1+p2= " + result);
}
}

/**
* 這是一個內部類
* 單項式的表示
*/
class Monomial {
int coefficient; // 系數
int index; // 指數
Monomial next; // 後繼結點

public Monomial() {
}

public Monomial(int c, int i) {
this.coefficient = c;
this.index = i;
}
}

閱讀全文

與java兩多項式相加相關的資料

熱點內容
文件夾中搜索文件的方法有哪些 瀏覽:890
win7系統刪除c盤非系統文件 瀏覽:225
百度地圖json代碼 瀏覽:765
如何將xml導入資料庫 瀏覽:395
編程和英語哪個好 瀏覽:474
網店編程軟體有哪些 瀏覽:196
真假的蘋果手機對比圖片 瀏覽:503
彩電內存數據用什麼軟體 瀏覽:975
計算機網路課本 瀏覽:486
大數據書的結構是什麼 瀏覽:409
蘋果7手機代碼查詢步驟 瀏覽:372
如何辦理網路教育 瀏覽:643
ps保存文件亂碼了 瀏覽:23
電腦傳文件到手機一會停止 瀏覽:363
怎麼把word保存為pdf文件 瀏覽:803
怎麼恢復備份文件小米 瀏覽:620
年齡大適合學什麼編程語言 瀏覽:201
榮耀9文件夾怎麼改名字 瀏覽:113
奔跑吧哪個app可以看 瀏覽:646
做教研的數據哪裡找 瀏覽:162

友情鏈接