HITSZkk 2016-04-19 14:33 采纳率: 0%
浏览 1403

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条回答 默认 最新

  • threenewbee 2016-04-19 21:19
    关注
    评论

报告相同问题?

悬赏问题

  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置