最近数据结构刚好学到链表,在此写了一个多项式相加的小程序,以下是伪代码,方便大家看懂:
算法attch(c,e, d) 建立一个新结点,其系数coef=c,指数exp=e;
并把它链到 d 所指结点之后,返回该结点指针。
polypointer attch ( int c , int e , polypointer d )
{ polypointer x ;
x = new polynode ;
x→coef = c ;
x→exp = e ;
d→link = x ;
return x ;
} ;
算法 padd实现两个多项式
a,b 相加;
c(x)= a(x) + b(x)
polypointer padd ( )
polypointer a , polypointer b ;
{ polypointer p, q, d, c ;
int x ;
p = a→link ; q = b→link ;
c = new polynode ; d = c ;
while ( (p != NULL) && (q !=NULL) )
switch ( compare ( p→exp, q→exp ) )
{ case ‘=‘ :
x = p→coef + q→coef ;
if ( x ) d = attch( x, p→exp, d ) ;
p = p→link ; q = q→link ;
break ;
case ‘>’:
d = attch( p→coef, p→exp,d );
//以下为具体实现的C++代码:
#include <iostream>
#include <bits/stdc++.h>#define LEN sizeof(struct pionter)
#include <stdio.h>
using namespace std;
struct pionter
{
int ceof;
int exp;
struct pionter *next;
};
//建立链表
struct pionter *Create()
{
int n = 0;
pionter *node1=NULL;//保存当前节点
pionter *node2;//记录新开辟节点
pionter *head;
node2 = (struct pionter *)malloc(LEN);
node1 = node2;
if(node2 == NULL)
{
cout<<"error!"<<endl;
}
else
{
head = NULL;
cout<<"Input the ceof and exp: ";
cin>>node2->ceof>>node2->exp;
}
if(node2->exp==0)
{
head = node2;
head->next = NULL;
}
else
{
while(node2->exp!=0)
{
n = n+1;
if(n==1)
{
head = node2;
head->next = NULL;
}
else
{
node1->next = node2;
}
node1 = node2;
node2 = (struct pionter *)malloc(LEN);
cout<<"Input the ceof and exp: ";
cin>>node2->ceof>>node2->exp;
}
//将最后一个元素单独插入到链表尾部
node1->next = node2;
node1 = node2;
node1->next = NULL;
n = n+1;
}
return head;
}
//建立一个新的节点,ceof = c,exp = e,把它链接到d所指节点之后。
struct pionter *Attach(int c, int e, pionter *d)
{
pionter *x;
x = (struct pionter *)malloc(LEN);
x->ceof = c;
x->exp = e;
d->next = x;
return x;
};
//多项式相加的具体实现
struct pionter *Add(pionter *node1,pionter *node2)
{
pionter *p,*q,*d,*c;
int x;
p = node1,q = node2;
c = (struct pionter *)malloc(LEN);
d = c;
while((p!=NULL)&&(q!=NULL))
{
if(p->exp==q->exp)
{
x = p->ceof +q->ceof;
if(x != 0)
d = Attach(x, p->exp,d);
p = p->next;q = q->next;
}
else if(p->exp>q->exp)
{
d = Attach(p->ceof,p->exp ,d);
p = p->next;
}
else if(p->exp<q->exp)
{
d = Attach(q->ceof,q->exp,d);
q = q->next;
}
}
while(p!=NULL)
{
d = Attach(p->ceof,p->exp,d);
p = p->next;
}
while(q!=NULL)
{
d = Attach(q->ceof,q->exp,d);
q = q->next;
}
d->next=NULL;
p = c;c = c->next;free(p);
return c;
};
void Print(pionter *head)
{
pionter *p = head;
int flag = 0;
cout<<"The result is: "<<endl;
while(p != NULL)
{
if(p->ceof!=0)
{
cout<<p->ceof<<"\t"<<p->exp<<endl;
flag = 1;
}
p = p->next;
}
if(flag==0) cout<<0<<endl;
}
int main()
{
pionter *head1;
pionter *head2;
pionter *head3;
cout<<"Please input the first node."<<endl;
head1 = Create();//建立链表1
cout<<"Please input the second node."<<endl;
head2 = Create();//建立链表2
head3 = Add(head1, head2);
Print(head3);
return 0;
}