示例答案是对的,但是测试点2一直过不去,这是什么原因呢
代码在这
#include <iostream>
using namespace std;
struct Node {
float coef; //系数
int exp; //指数
Node *next; // 指针域
};
class LinkList {
public:
LinkList(); //无参构造函数
void create(int c[],int e[]); //尾插法构建链表
void printList(); //遍历输出
int getLength(); //获取链表的长度
Node *getfirst(); //返回头指针
private:
Node *first; //头节点指针
};
/*初始化*/
LinkList::LinkList() {
first = new Node();
first->next = NULL;
}
/*尾插法*/
void LinkList::create(int c[],int e[]){
first=new Node();
int i=0;
Node *real=first;
while(c[i]!=0){
/*if(c[i]!=0){*/
Node *s=new Node();
s->coef=c[i];
s->exp=e[i];
s->next=NULL;
real->next=s;
real=s;
i++;
}
real->next=NULL;
}
/*遍历*/
void LinkList::printList(){
Node *p=first->next ;
while(p!=NULL){
cout<<p->coef<<","<<p->exp<<" ";
p=p->next;
}
cout<<endl;
}
/*返回头指针*/
Node *LinkList::getfirst(){
return first;
}
/*合并同类项*/
void poly(LinkList &LA,LinkList &LB){
Node *p,*q,*ppre,*qpre,*t;
/*p指向LA的首元结点*/
/*ppre为p的前驱结点*/
ppre=LA.getfirst();
qpre=LB.getfirst();
p=ppre->next;
q=qpre->next;
while(p!=NULL&&q!=NULL){
/*p后移,q不动*/
if(p->exp<q->exp){
ppre=p;
p=p->next;
}
/*p不动,q插入p之前,ppre指向p,q指向下一个节点*/
else if(p->exp>q->exp){
t=q->next;
qpre->next=q->next;
q->next=p;
ppre->next=q;
ppre=q;
q=t;
}
/*指数相等时,合并*/
else if(p->exp==q->exp){
p->coef=p->coef+q->coef;
/*系数为0,删除p*/
if(p->coef==0){
t=p;
p=p->next;
ppre->next=p;
delete t;
}
/*删除q*/
t=q;
q=q->next;
qpre->next=q;
delete t;
}
}
if(q!=NULL){
ppre->next=q;
}
}
/*主函数*/
int main(){
system("color F0");
int i=0,j=0,e1[100],e2[100];
int c1[100],c2[100];
LinkList L1;
LinkList L2;
while(scanf("%d,%d",&c1[i],&e1[i]))
{
if(c1[i]==0&&e1[i]==0)
break;
i++;
}
L1.create(c1,e1);
//L1.printList();
while(scanf("%d,%d",&c2[j],&e2[j]))
{
if(c2[j]==0&&e2[j]==0)
break;
j++;
}
L2.create(c2,e2);
//L2.printList();
poly(L1,L2) ;
L1.printList();
return 0;
}
感谢解答!
应该都要逗号,或者都不要逗号吧,这样输入获取的数据不对。