最近的一个实验作业,要求用Java实现多项式的计算,书上的方法是将中序表达式先转化为后序表达式,然后进行运算。想到上学期实现真值表的时候用到的双栈方法,就尝试用双栈实现了一下,感觉要更好一些。最主要的是自己又把双栈敲了一遍,debug的同时也一点点把Java拾了起来,挺好。
代码实现:
节点类:
//定义节点类
class Lnode<T> implements Comparable<Lnode<T>> {
public T data;
public Lnode<T> next;
public Lnode(T key) {
data = key;
next = null;
}
public Lnode(T key, Lnode<T> next) {
data = key;
this.next = next;
}
public boolean equals(Lnode<T> e) {
return data.equals(e);
}
// 比较器
public int compareTo(Lnode<T> e) {
Comparable<T> x;
if (data instanceof Comparable) {
x = (Comparable<T>) data;
return (int) x.compareTo(e.data);
} else
throw new ClassCastException("类型无法比较!");
}
// 重载toString
public String toString() {
return data.toString();
}
}
栈:
public class LinkList<T> {
Lnode<T> first, last;// 首指针和尾指针
int num;// 元素个数
// 比较其,内部使用
private int compare(Lnode<T> a, Lnode<T> b) {
return a.compareTo(b);
}
// 构造函数
public LinkList() {
first = last = null;
num = 0;
}
// 判断链表是否空
public boolean isEmpty() {
return first == null;
}
// 删除整个链表
public void clear() {
first = last = null;
num = 0;
}
// 求链表长度
public int length() {
return num;
}
public int size() {
return num;
}
// 内部使用,取得第i号结点的指针
protected Lnode<T> getNode(int i) {
if (i < 0 || i > num - 1)
return null;
if (i == 0) {
return first;
}
Lnode<T> p = first;
int j = 0;
while (p != null && j < i) {
p = p.next;
j++;
}
return p;
}
public T get(int i) {
Lnode<T> p = getNode(i);
if (p == null)
return null;
else
return p.data;
}
public boolean set(int i, T x) {
Lnode<T> p = getNode(i);