单链表表示多项式笔记:
- 多项式的项作为节点插入
Term *Term::InsertAfter(int c, int e){
//在当前由this指针指示的项(即调用此函数的对象后)插入一个新项
link = new Term(c, e, link);
return link;
}
2. 多项式的输出,通过节点类中的运算符重载
//类中定义
friend ostream& operator <<(ostream&, const Term&);
ostream& operator <<(ostream& out, const Term& x){
if(x.coe == 0.0) return out;
out << x.coe;
switch(x.coe){
case 0: break;
case 1: out << "X";break; //处理当其为1时
default: out << "X^" << x.exp; break;
}
}
- 同理,多项式的类输出和***输入***
节点的输出是为了方便的表示类输出
istream& operator>>(istream& in, Polynomal& x){
Term *rear = x.getHead(); int c, e;
while(1){
cout << "输入新节点:"<<endl;
in >> c >> e;
if(e < 0) break; //使用e<0,控制输入结束
rear = rear->InsertAfter(c, e); //尾插法,链接到rear所指的指针后
return in;
}
}
输出
ostream& operator << (ostream& out, Polynomal& x){
Term *current = x.getHead()->link;
cout <<"多项式" <<endl;
bool h = true;
while(current != NULL){
if(h = false && current->coe > 0.0) out << "+";
h = false;
out << *current;
current = current->link;
}
out << endl;
return out;
};