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 请教:如何用postman调用本地虚拟机区块链接上的合约?
  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?
  • ¥15 乘性高斯噪声在深度学习网络中的应用
  • ¥15 运筹学排序问题中的在线排序
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛