2 hfutkk 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 changehead(node *h);
int add(Lpoly A, Lpoly B);
private:
int count;
node * head;
};
Lpoly::Lpoly() { //多项式初始化
head = new node;
head->coef = 0;
head->exp = 0;
head->next = NULL;
count = 0;
}
int Lpoly::insert(int x, int z) { //向多项式中添加项
node *p;
p = head;
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;
p = head;
if (count == 0) {
cout << "该多项式为空"< return success;
}
p = head->next;
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) {
head = h;
return 1;
}
int Lpoly::add(Lpoly A,Lpoly B) { //求和,把A,B和给C
node *pa, *pb;
node *r;
head = A.get_head();//C的头指针指向A
r = head; //连接用的指针
pa = A.get_head()->next;
pb = B.get_head()->next;
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.add(A, B);
C.print();
//cout << "234";
return 0;
}


2个回答

caozhy
caozhy   Ds   Rxr 2016.04.20 05:19
qq423399099
qq423399099   Ds   Rxr 2016.04.20 10:58

单步调试和设断点调试(VS IDE中编译连接通过以后,按F10或F11键单步执行,按Shift+F11退出当前函数;在某行按F9设断点后按F5执行停在该断点处。)是程序员必须掌握的技能之一。

Csdn user default icon
上传中...
上传图片
插入图片