ex4.cpp
来自「上海交通大学本科算法大作业」· C++ 代码 · 共 156 行
CPP
156 行
#include<iostream>
#include<sstream>
#include<string>
#include<fstream>
using namespace std;
struct polynode
{
polynode *next;
int a,e;//ax^e
};
class poly
{
protected:
polynode *head,*tail;
void additem(int a,int e);
void add(int,int);
public:
poly(){head=tail=NULL;};
poly(char*,int);
poly(poly&);
~poly();
void display();
friend void operator*(poly&,poly&);
};
void poly::additem(int a,int e)
{
polynode *p=new polynode;
p->a=a;
p->e=e;
p->next=NULL;
if(tail==NULL)
{
head=p;
}
else
{
tail->next=p;
}
tail=p;
}
poly::poly(char *str, int n)
{
char *prestr;
int t,a;
t = n;
head=tail=NULL;
istringstream stream(str);
while(stream >> a)
additem(a,t--);
return;
}
poly::poly(poly& t)
{
polynode *p;
if((p=t.head)==NULL)
{
head=tail=NULL;
return;
}
head=tail=new polynode;
head->a=p->a;
head->e=p->e;
head->next=NULL;
p=p->next;
while(p)
{
add(p->a,p->e);
p=p->next;
}
}
poly::~poly()
{
polynode *p=head,*prep;
while(p)
{
prep=p;
p=p->next;
delete prep;
}
}
void poly::display()
{
polynode *p=head;
ofstream fout("result1.txt");
while(1)
{
fout<<p->a;
p=p->next;
if(p)fout<<" ";
else break;
}
fout<<endl;
fout.close();
}
void poly::add(int a,int e)
{
polynode *p=head;
if(p==NULL)
{
head=tail=new polynode;
tail->a=a;
tail->e=e;
tail->next=NULL;
}
else
{
while(p&&p->e!=e)p=p->next;
if(p==NULL)
{
p=new polynode;
p->a=a;
p->e=e;
p->next=NULL;
tail->next=p;
tail=p;
}
else
{
p->a+=a;
}
}
}
void operator*(poly& f1,poly& f2)
{
int a,e;
poly rst;
polynode *p,*q;
if(f1.head==NULL||f2.head==NULL)
{
poly tmp("0",0);
return ;
}
for(p=f1.head;p!=NULL;p=p->next)
for(q=f2.head;q!=NULL;q=q->next)
{
a=p->a*q->a;
e=p->e+q->e;
rst.add(a,e);
}
rst.display();
}
int main()
{
char str1[255],str2[255];
int n;
ifstream fin("data1.txt");
fin >> n ;
fin.getline(str1,255);
fin.getline(str1,255);
fin.getline(str2,255);
poly a(str1,n),b(str2,n);
a*b;
fin.close();
return 0;
}
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?