当前位置: 代码迷 >> 综合 >> PTA 1002. A+B for Polynomials C++ 链表实现
  详细解决方案

PTA 1002. A+B for Polynomials C++ 链表实现

热度:32   发布时间:2023-11-20 23:36:43.0

提示:问题主要出在格式上面。

1,当多项式相加系数全部抵消时,输出应该为 0,而不是为 0 0 0.0 之类的。即只需输出项数。

2,输出的系数的小数部分可能超过一位,输出是应该保留一位小数。

#include <iostream>
#include <iomanip>using namespace std;
struct Data//多项式的数据类型
{int exp;//指数double coe;//系数
};typedef Data ElemType;struct NodeType //多项式节点
{ElemType data;NodeType * next;
};//单链表
class LinkList{
private:NodeType *Head;int lenth;
public:LinkList();~LinkList();void Creat();void Print();void Insert(int i,ElemType x);ElemType Delete(int i);NodeType* GetHead();};
LinkList::LinkList()
{Head = new NodeType;Head->next = NULL;Head->data.coe = 0;Head->data.exp = 0;
}
LinkList::~LinkList()
{NodeType *p = Head->next;while(p!= NULL){Head->next = p->next;delete p;p = Head->next;}delete Head;
}
void LinkList::Creat()
{NodeType *last = Head,*p;int i = 0,x;double y;cin >> i ;for(int j = 0;j<i;j++){cin >> x >> y;p = new NodeType;p->data.exp = x;p->data.coe = y;p->next = NULL;last->next = p;last = p;p = NULL;}
}
NodeType* LinkList::GetHead()
{return Head;
}//多项式相加函数
NodeType * polyAdd(LinkList &a,LinkList &b) 
{//为了节省节点空间,在此不创建新节点,利用链表a,b的节点生成新节点。r指向新生成的节点,p指向a链表的当前节点,q指向b链表的当前节点。rt返回新建节点的头节点地址。NodeType *r,*p,*q,*rt;r = a.GetHead();rt = r;p = r->next;q = b.GetHead()->next;while(p!= NULL && q!= NULL){if(p->data.exp == q->data.exp){double x = p->data.coe+q->data.coe;if(x == 0)r->next = p->next;else{p->data.coe = x;r->next = p;r = p;}p = p->next;q = q->next;}else if(p->data.exp > q->data.exp){r->next =p;r = p;p = p->next;}else{r->next = q;r = q;q = q->next;}}if(p == NULL)r->next = q;elser->next = p;return rt;
}
void Print(NodeType *p)
{int counter = 0;NodeType *q = p->next;p = p->next;while(q!= NULL){q = q->next;counter++;}cout << counter;while(p!=NULL){cout << " " << p->data.exp <<" " <<setiosflags(ios::fixed)<<setprecision(1) << p->data.coe ;p = p->next;}}int main()
{LinkList poly1,poly2;NodeType * np;poly1.Creat();poly2.Creat();np =polyAdd(poly1,poly2);Print(np);return 0;
}