我是一个c++新手,求一个单链表的程序
求用单链表表示的多项式相加的程序。求哪位高手给个c++代码看看。
程序代码:#include <iostream>
using namespace std;
struct T
{
int coef;
int exp;
};
struct Node
{
T ax;
Node *next;
};
class LinkList
{
public:
LinkList( ){first = NULL;}
LinkList(T a[], int n);
~LinkList( );
void plus(LinkList &);
void insert(Node *q);
void show();
Node *getFirst( ){ return first;}
private:
Node *first;
};
LinkList::LinkList(T a[], int n) //创建链表
{
first = new Node;
first->next = NULL;
for(int i=0; i<n; i++)
{
Node *p = new Node;
p->ax.coef = a[i].coef;
p->ax.exp = a[i].exp;
p->next = first->next;
first->next = p;
}
}
LinkList::~LinkList() //释放结点
{
Node *p = first;
while(p)
{
Node *q = p;
p = p->next;
delete q;
}
}
void LinkList::plus(LinkList &B) //多项式相加
{
if(!first) first = B.getFirst( );
else{
if(!B.getFirst() || !B.getFirst()->next) return;
else{
if(first->next==NULL)
first->next = B.getFirst( )->next;
else{
Node *p1 = first, *q1 = B.getFirst( );
Node *p = p1->next, *q = q1->next;
while(p && q)
{
if(p->ax.exp < q->ax.exp)
{ p1 = p; p = p->next;}
else if(p->ax.exp > q->ax.exp)
{
q1->next = q->next;
p1->next = q;
q->next = p;
p1 = p1->next;
q = q1->next;
}
else if(p->ax.exp == q->ax.exp)
{
p->ax.coef = p->ax.coef + q->ax.coef;
if(p->ax.coef==0)
{
Node *pt = p;
p1->next = p->next;
p = p1->next;
delete pt;
}
else {p1 = p; p = p->next;}
Node *qt = q;
q1->next = q->next;
q = q->next;
delete qt;
}
}
if(q) p1->next = q;
}
}
}
}
void LinkList::show()
{
cout<<"多项式 = ";
Node *p = first;
while(p&&p->next)
{
p = p->next;
cout<<p->ax.coef<<'X'<<p->ax.exp;
if(!p->next) cout<<endl;
else cout<<" + ";
}
}
void main(void)
{
T a[3] = {{2,3},{4,2},{5,1}};
LinkList A(a, 3);
A.show();
T b[2] = {{6,4},{7,2}};
LinkList B(b, 2);
B.show();
A.plus(B);
A.show();
}
