用C++写多项式相加算法,运行出现问题,求解
#include <iostream>
using namespace std;
struct Term {
double cofe;
int exp;
Term* link;
Term(double c , int e , Term* next = NULL) {
cofe = c;
exp = e;
link = next;
}
Term() {
cofe = 0;
exp = 0;
link = NULL;
}
Term* insertTerm(double c , int e) {
link = new Term(c,e,link);
return link;
}
};
typedef Term* LinkPoly;
LinkPoly create();
LinkPoly addPlus(LinkPoly &L,LinkPoly &M);
void print(LinkPoly &W);
int main() {
cout<<"创建两个多项式:"<<endl;
LinkPoly Lpoly = create();
LinkPoly Mpoly = create();
LinkPoly W = addPlus(Lpoly,Mpoly);
print(W);
return 0;
}
LinkPoly create() {
LinkPoly p1,p2,head;
head = NULL;//创建一个空表
p1 = new Term;
p2 = p1;
cin>>p1 -> cofe>>p1 ->exp;
while (p1 -> exp != -1) {
if (head == NULL) {
head = p1;
}
else {
p2 -> link = p1;//将链表连接起来
}
p2 = p1;
p1 = new Term;
cin>>p1 -> cofe>>p1 -> exp;
}
p2 -> link = NULL;
delete p1;
return head;
}
void print(LinkPoly &W) {
LinkPoly p;
p = W;
if (p == NULL) {
cout << "链表是空表!" << endl;
}
else {
while (p -> link != NULL) {
cout<<"("<<p -> cofe<<","<<p -> exp<<")"<<" -> ";
p = p -> link;
}
cout<<"("<<p -> cofe<<","<<p -> exp<<")"<<endl;
}
}
LinkPoly addPlus(LinkPoly &L,LinkPoly &M) {
LinkPoly N = NULL;
LinkPoly A = L;
LinkPoly B = M;
LinkPoly p;
while (A -> link != NULL && B -> link != NULL) {
if (A -> exp == B -> exp) {
double temp = A -> cofe + B -> cofe;
if (temp != 0) {
N = N -> insertTerm(temp,A ->exp);
}
A = A -> link;
B = B -> link;
}
else if (A -> exp < B ->exp) {
N = N -> insertTerm(A ->cofe,A ->exp);
A = A -> link;
}
else {
N = N -> insertTerm(B ->cofe,B ->exp);
B = B -> link;
}
}
if (A != NULL) {
p = A;
}
else p = B;
while (p != NULL) {
N = N -> insertTerm(p -> cofe ,p -> exp);
p = p ->link;
}
return N;
}
七夜D战车
9 years, 4 months ago
Answers
所以是遇到 SegmentFault 就来 SegmentFault 求助了么……
新手遇到 segfault 其实很正常,此时可以善于使用 GDB。使用 GDB 跑一下你的代码,使用 bt 命令打印一下调用栈:
#0 0x0000000000400f5a in Term::insertTerm (this=0x0, c=1, e=2) at tmp.cpp:24
#1 0x0000000000400db9 in addPlus (L=@0x7fffffffdf48: 0x603010,
M=@0x7fffffffdf50: 0x6030c0) at tmp.cpp:111
#2 0x0000000000400aa6 in main () at tmp.cpp:42
可以发现,addPlus 函数中初始的 N 是 NULL,而你直接调用 N 的方法,就出现了 this 为 NULL 的情况。deference 一个空指针自然会导致 segfault。
至于怎么解决,你应该可以自己想明白。
8158432
answered 9 years, 4 months ago