|
【測試代碼】 protected void calc(TextView tv) { Expression exp = new Expression(); exp.add(4, 0); exp.add(8, 2); exp.add(6, 1); exp.add(9, 3); exp.add(-7, 5); exp.add(-8, 2); exp.add(-3, 5); String str = "a=" + exp.toString() + '\n'; Expression exp2 = new Expression(); exp2.add(-4, 0); exp2.add(-6, 1); exp2.add(-7, 2); exp2.add(1, 10); exp2.add(8, 4); exp2.add(-1, 6); exp2.add(10, 5); str += "b=" + exp2.toString() + '\n'; exp.add(exp2); str += "a+b=" + exp.toString();
tv.setText(str); }
|
|
package com.oct1158.javatest;
public class Expression extends LinkList { public int add(Item item) { int i = 0; LinkData p = link; for (i = 0; p != null; i++) { Item data = (Item)p.data; if (data.power == item.power) { data.coef += item.coef; if (data.coef == 0) { delete(i); } return -1; } else if (data.power > item.power) { break; } p = p.next; } insert(i - 1, item); return i; } public int add(double coef, int power) { return add(new Item(coef, power)); } public void add(Expression exp) { LinkData p = exp.link; while (p != null) { add((Item)p.data); p = p.next; } } @Override public String toString() { LinkData p = link; String str = ""; while (p != null) { Item item = (Item)p.data; if (p != link) { if (item.coef > 0) { str += '+'; } } str += item.coef; if (item.power == 1) { str += 'x'; } else if (item.power != 0) { str += "x^" + item.power; } p = p.next; } return str; } }
|
|
package com.oct1158.javatest;
public class LinkList { LinkData link; /*public LinkData append(Object obj) { int i = getLength() - 1; return insert(i, obj); }*/ public Object delete(int i) { Object obj; if (i == 0) { obj = link.data; link = link.next; // 若所有節點都被刪除了, 則this.link = null } else { LinkData p = get(i - 1); if (p == null || p.next == null) { return null; } obj = p.next.data; p.next = p.next.next; } return obj; } public LinkData get(int i) { LinkData data = link; for (; i > 0; i--) { data = data.next; if (data == null) { break; } } return data; } public int getLength() { int i; LinkData data = link; for (i = 0; data != null; i++) { data = data.next; } return i; } public LinkData getRear() { LinkData data = link; if (data == null) { return null; } while (data.next != null) { data = data.next; } return data; } // 在i的後面插入 public LinkData insert(int i, Object obj) { LinkData q = new LinkData(obj); if (i == -1) { q.next = link; // -1.next = link link = q; } else { LinkData p = get(i); if (p == null) { return null; } q.next = p.next; p.next = q; } return q; } }
|
|
package com.oct1158.javatest;
public class LinkData { public Object data; public LinkData next = null; public LinkData(Object data) { this.data = data; } }
|
|
package com.oct1158.javatest;
public class Item { public double coef; public int power; public Item(double coef, int power) { this.coef = coef; this.power = power; } }
|
|
【運行結果】
|