利用链表计算多项式的相加

// list1.cpp : 定义控制台应用程序的入口点。
//


#include "stdafx.h"
#include <stdlib.h>
#include <stdio.h>
#include <iostream>
using namespace std;


//typedef ElemType int;
typedef struct {
float coef;    //系数
int expn;      //指数
}term,ElemType;


typedef struct LNode {
ElemType data;
struct LNode *next;
}LNode,*LinkList;






void CreatList(LinkList &L)
{   
//创建多项式,根据用户的输入结果来创建整个链表,
//如果系数为0,则表明输入结束


float coef;
int expn;
LinkList temp;
L = (LinkList) malloc (sizeof(LNode));
L->next=NULL;
temp=L;
cout<<"输入系数和指数";
cin>>coef>>expn;
while(coef !=0 )
{
LinkList p;
p=(LinkList) malloc (sizeof(LNode));
p->data.coef=coef;
p->data.expn=expn;
p->next=NULL;
temp->next=p;
temp=temp->next;
cout<<endl;
cout<<"输入系数和指数";
cin>>coef>>expn;
}
}


void PrintList(LinkList L)
{
//输出链表的值
L=L->next;
while (L!=NULL)
{
cout<<L->data.coef<<"  "<<L->data.expn<<endl;
L=L->next;
}
}


void AddList(LinkList L1,LinkList L2)
{
//由于这里的L1等参数是通过参数传递的,所以原来的值并没有改变
//不需要像书中那样用&L1来传入参数的地址
LinkList p1=L1->next;
LinkList p2=L2->next;          //链表的指针总是成对出现,这样可以简化操作


while ( p1&& p2)
{
if (p1->data.expn == p2->data.expn)
{
//这里面省略了两者相加,系数等于0的情况!!
p1->data.coef += p2->data.coef;
L1=p1;
p1 = p1->next;
free(L2);
   L2=p2;
p2=p2->next;
}



else if (p1->data.expn<p2->data.expn)
{
L1=L1->next;
p1=p1->next;
continue;
}


else if (p1->data.expn>p2->data.expn)
{
L1->next=p2;
L2=p2->next;
p2->next=p1;
p2=L2;


}


    }
if(p2)  L1->next=p2;   //若L2还有剩余的部分,加到L1的后面


}






int _tmain(int argc, _TCHAR* argv[])
{
LinkList L1,L2;
CreatList(L1);
cout<<"请输入第二个多项式"<<endl;
CreatList(L2);
AddList(L1,L2);
PrintList(L1);


return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值