线性表的链式存储实现及应用
实验目的
- 掌握抽象数据类型ADT的定义、表示和实现。
- 掌握线性表的基本结构和操作方法。
- 培养学生灵活使用数据结构解决实际问题的能力。
实验内容
采用链表方案实现两个一元多项式求和。要求:
- 利用链表结点的方式,定义恰当的数据类型来表示多项式的每一项。
- 通过键盘输入两个一元多项式Pn(x)和Qm(x),其中,多项式各项的输入顺序随意,计算多项式Pn(x)和Qm(x)求和的结果,并按照变量x的幂次递减顺序显示。例如: Pn(x) = 9x15 +7x8 + 5x3 + 3x; Qm(x) = -7x8 + 6x3 + 2; 则 Pn(x) + Qm(x) = 9x15 + 11x3 + 3x + 2
- (选做)在求和实现方案基础上,尝试利用两个一元多项式求和的算法实现两个一元多项式相乘。(提示:先利用公式 ,将两个一元多项式的乘法转换为计算多个一元多项式求和,然后连续调用之前的求和算法,最终计算出两个一元多项式相乘的结果。)
代码:
#include <stdlib.h>
#include <stdio.h>
struct node //创建结构体,包含系数,指数,指针
{
int n;
float c;
node *next;
};
node *create(char M ) //创建链表,存放多项式
{
int n=0;
float c=0;
node *head=NULL,*p1=NULL,*p2=NULL;
cout<<"请按指数升序输入多项式"<< M <<"的系数,以回车结束:";
do
{
cin>>c;
if(c) //存放系数不为零的项
{
p1=new node;
p1->c=c;
p1->n=n;
if (head==NULL) head=p1;
else p2->next=p1;
p2=p1;
p1->next=NULL;
}
n++;
}while(cin.get()!='\n');
return head; //返回头指针
}
node *fun(node *A ,node *B) //多项式求和
{
int n;
node *p=NULL,*q=NULL,*head; //用于标记A的上一个节点
head=A ; //标记头节点
while(A!=NULL&&B!=NULL) //逐项比较直到一个多项式结束
{
if(A->n - B->n==0)
{
A->c=A->c+B->c ; //同幂指数相加
if(A->c) p = A ; //若和非零,保留A地址
else //否则删去此项
{
if(p!=NULL) {p->next = A->next ; A = A->next;}
else {head=A->next;}
}
A = A->next; //AB向后一项移动
B = B->next ;
}
else if(A->n - B->n<0)
{
p = A ; A = A->next; //保留A地址,A向下一项
}
else
{
if(p == NULL)
{
q=B->next ; //保存B->next
B->next= A ; //将B插至A前
head = B; //头节点变为B
p=A ;B =q; //保留A地址,B向下一项
}
else
{
p->next = B ; //将B插至A前
B->next = A ;
B = B->next ; //B向下一项
}
}
}
if(A==NULL) p->next = B; //A结束,将B剩余项复制至A尾
return head;
}
void print(node *head) //输出函数
{
node *p;
p=head;
for(;head!=NULL;head=head->next)
{
if(head==p) cout<<head->c;
else if(head!=p)
{
if(head->c>0&&head->c!=1) cout<<"+"<<head->c;
if(head->c==1) cout<<"+";
if(head->c<0&&head->c!=-1) cout<<head->c;
if(head->c==-1) cout<<"-";
}
if(head->n!=0) cout<<"x";
if(head->n!=1&&head->n!=0) cout<<"^"<<head->n;
}
}
int main()
{
char A='A' ,B='B';
node *head1,*head2,*result;
head1=create(A);
head2=create(B);
result=fun(head1,head2);
cout<<"求和结果为:"<<endl;
print(result);
return 0;
}