问题描述
- c++ 内存问题 找了好久都不知道呢错了
-
#include<iostream>
using namespace std;
struct Node
{
float coef;//系数
int expn;//指数
Node* next;
};class Ploy
{
public:
Ploy();
~Ploy();
void CreatePloy(int n);
void DispPloy();
void PloyAdd(Ploy b);
Node* GetNode()
{
return head;
}
int compare(const Node *p1,const Node *p2)
{
if(p1->expn < p2->expn)//小于
return -1;
else if(p1->expn == p2->expn)//等于
return 0;
else //大于
return 1;
}
private:
Node *head;};
Ploy::Ploy()
{
head = new Node;
head->next = NULL;
}
Ploy::~Ploy()
{
Node *p;while(head) { p = head; head = head->next; delete p; } head = NULL; cout<<"xigou is running"<<endl;
}
void Ploy::CreatePloy(int n)
{
int i=1;
Node *p,*s;
p = head;
for (i;i<=n;i++)
{
cout<<"请输入第"<<i<<"项(系数,指数);";
s = new Node;cin>>s->coef; cin>>s->expn; s->next = p->next; p->next = s; p = s; }
}
void Ploy::DispPloy()
{
Node p;
p = head;
while(p->next != NULL)
{
p = p->next;
cout<coef<<""<<"x"<<"^"<expn<<"+";
}
cout<<endl;
}void Ploy::PloyAdd(Ploy p_b)
{
Node *pa,*pb,*psum;
Ploy p_sum;
pb = p_b.GetNode()->next;
pa = head->next;
psum = p_sum.GetNode();
//psum->next = head->next;
int sum;while(pa && pb) { switch(compare(pa,pb)) { case -1:psum->next = pa; psum = pa; pa = pa->next; break; case 0: sum = pa->coef + pb->coef; pa->coef = sum; psum->next = pa; psum = pa; pa = pa->next; pb = pb->next; break; case 1:psum->next = pb; psum = pb; pb = pb->next; break; } } psum->next = pa?pa:pb; p_sum.DispPloy();
}
int main()
{
Ploy p1,p2;
p1.CreatePloy(5);
p1.DispPloy();
p2.CreatePloy(5);
p2.DispPloy();
p1.PloyAdd(p2);
p1.DispPloy();
return 0;}
这个是实现多项式加法的 但不知道呢出错了 希望各位前辈帮忙看看 报的_block_type_is_valid