hfutkk 于 2016.04.19 22:33 提问

c++实现多项式相加，加法函数不知道为什么是死循环，调了好久没弄出来，求教

#include
using namespace std;
enum error_code { success, overflow, arrange_error };
static int num;
struct node {

``````int coef;
int exp;
node * next;
``````

};
class Lpoly {
public:
Lpoly();
int print();
int insert(int x, int y);
int length() { return count; }
node * get_head() { return head; }
int add(Lpoly A, Lpoly B);
private:
int count;
};
Lpoly::Lpoly() { //多项式初始化
head = new node;
count = 0;
}
int Lpoly::insert(int x, int z) { //向多项式中添加项
node *p;
node *q;
q = p;
if(p->next!=NULL)p = p->next;
while(p->exp>z&&p!=NULL){
if (p->next->expnext!=NULL) {
q = p;
}
p = p->next;
}
if (p->exp == z) {
p->coef += x;
return success;
}

``````else if (p->exp<z) {
node* temp=new node;
temp->coef = x;
temp->exp = z;
temp->next = p;
q->next = temp;
count++;
return success;
}
else if (p->next == NULL) {
node* temp = new node;
temp->coef = x;
temp->exp = z;
temp->next = NULL;
p->next = temp;
count++;
return success;
}
``````

}
int Lpoly::print() {
node *p = new node;
if (count == 0) {
cout << "该多项式为空"< return success;
}
while (p->exp!=0) {
if (p != head->next && (p->coef > 0))
cout << '+';
cout << p->coef << 'X' << p->exp;
p = p->next;
}
cout << endl;
return success;
}
int Lpoly::changehead(node *h) {
return 1;
}
int Lpoly::add(Lpoly A,Lpoly B) { //求和，把A,B和给C
node *pa, *pb;
node *r;
r = head; //连接用的指针
while (pa != NULL&&pb != NULL) {
if (pa->exp == pb->exp) {
int t;
t = (pa->coef) +(pb->coef);
if (t != 0) {

pa->coef = t;
r->next = pa;
r = pa;
}
pa = pa->next;
pb = pb->next;
}
else if (pa->exp > pb->exp) {
r->next = pa;
r = pa;
pa = pa->next;
}
else {
r->next = pb;
r = pb;
pb = pb->next;
}
}
if (pa == NULL)
r->next = pb;
else
r->next = pa;
cout << 12345 << endl;
return success;
}
int main() {
Lpoly A,B,C;
A.insert(3, 3);
A.insert(3, 5);
A.insert(3, 1);
A.insert(3, 4);
A.print();
B.insert(3, 3);
B.insert(3, 2);
B.insert(3, 5);
B.print();
C.print();
//cout << "234";
return 0;
}

``````
``````

2个回答

caozhy      2016.04.20 05:19
qq423399099      2016.04.20 10:58