数据结构——多项式相加

  
    
#include < iostream >
using namespace std;

struct linkpolyn
{
int coef;
int expn;
struct linkpolyn * next;
};
typedef
struct linkpolyn LinkPolyn;

// 创建链表函数
LinkPolyn * Creat()
{
LinkPolyn
* h, * p;
h
= (LinkPolyn * ) malloc( sizeof (LinkPolyn));
h
-> next = NULL;
LinkPolyn
* temp;
temp
= h;
cout
<< " 请输入: " << endl;
do
{
p
= (LinkPolyn * ) malloc( sizeof (LinkPolyn)); // 给第一个节点分配内存
cin >> p -> coef >> p -> expn;
if (p -> coef == 0 && p -> expn == 0 )
break ;
p
-> next = temp -> next;
temp
-> next = p;
temp
= p;
}
while ( 1 ); // 以0结束输入
return h;
}
// end creat

// 打印输出函数
void PrintPolyn(LinkPolyn * h)
{
LinkPolyn
* p1;
p1
= h -> next;
if (h -> next == NULL)
{
cout
<< " Polyn is empty! " << endl;
}
else
{
while (p1 != NULL)
{
cout
<< p1 -> coef << " x^ " << p1 -> expn << " + " ;
p1
= p1 -> next;
}
cout
<< " end " << endl;
}
}
// end printPolyn


// 表达式相加
LinkPolyn * add_Polyn(LinkPolyn * ha , LinkPolyn * hb)
{
LinkPolyn
* pa, * pb;
pa
= ha -> next;
pb
= hb -> next;
LinkPolyn
* prea, * preb;
prea
= ha;
preb
= hb;

while (pa && pb)
{
if (pa -> expn < pb -> expn)
{
prea
= pa;
pa
= pa -> next;
}
else if (pa -> expn == pb -> expn)
{
if (pa -> coef + pb -> coef != 0 )
{
pa
-> coef += pb -> coef;
prea
= pa;
}
else
{
prea
-> next = pa -> next;
}
preb
-> next = pb -> next;
pa
= pa -> next;
pb
= pb -> next;
}
else
{
preb
-> next = pb -> next;
pb
-> next = pa;
prea
-> next = pb;

pb
= preb -> next;
prea
= prea -> next;
}
}

if (pb) // 讲多项式B中未完成的链接到A山去
{
prea
-> next = pb;
}
return ha;
}

int main()
{
LinkPolyn
* head1;

// 创建多项式1
head1 = Creat(); // head1接受返回的指向头结点指针
PrintPolyn(head1);

// 创建多项式2
LinkPolyn * head2;
head2
= Creat(); // head1接受返回的指向头结点指针
PrintPolyn(head2);

// 多项式相加
LinkPolyn * head3;
head3
= add_Polyn(head1 , head2); // 指针要更新
PrintPolyn(head3); // 输出相加后的表达式
return 0 ;
}

 

你可能感兴趣的:(数据结构)