一元多项式的相加 数据结构链表实现

#include
#include
typedef struct Node
{
	float coe;               //系数
	int index;               //指数
	Node *next;
}*polynomial;                    //操作名

void Initpolynomial(polynomial &L)       //创建链表的头结点
{
	polynomial P = (polynomial)malloc(sizeof(Node));
	P->next =NULL;
	P->coe = -1.0;
	P->index = -1;
	L = P;
}

void Createpolynomial(polynomial &L,float coe,int index)      //在链表尾部输入数据
{
	polynomial P = (polynomial)malloc(sizeof(Node));
	P->coe = coe;
	P->index =index;
	polynomial S = (polynomial)malloc(sizeof(Node));  //用来调整在链表末尾输入数据
	S = L;
	while(S->next)
		S = S->next;
	P->next = S->next;
	S->next = P;
}

void showpolynomial(polynomial L)                       //用来输出链表
{
	while(L)
	{
		printf("(系数%.2f 指数%d)",L->coe,L->index);
		L = L->next;
	}

	printf("\n");
}


polynomial Addpolymial(polynomial Pa,polynomial Pb)   //表一 表二 相加结果存放在表三中
{
	polynomial head = (polynomial)malloc(sizeof(Node));   //主要是几个对象的问题需要两个来移动一个来存储一个来当头结点 最后返回///头结点这就是核心
	Initpolynomial(head);
	polynomial qa,qb,r,s;               //qa qb操作 r存放头结点 s 中转站
	r = head;
	qa = Pa->next;
	qb = Pb->next;
	while(qa&&qb)
	{
		polynomial s = (polynomial)malloc(sizeof(Node));
		if(qa->index < qb->index)
		{
			s->coe = qa->coe;
			s->index = qa->index;
			qa = qa->next;
		}
		else if(qa->index > qb->index)
		{
			s->coe = qb->coe;
			s->index = qb->index;
			qb = qb->next;
		}
		else
		{
			s->coe = qa->coe + qb->coe;
			s->index = qa->index;
			qa = qa->next;
			qb = qb->next;
		}
		r->next = s;
		r = r->next;
	}
	while(qa)
	{
		polynomial s = (polynomial)malloc(sizeof(Node));
		s->coe = qa->coe;
		s->index = qa->index;
		r->next = s;
		r = s;
		qa = qa->next;
	}
	while(qb)
	{
		polynomial s = (polynomial)malloc(sizeof(Node));
		s->coe = qb->coe;
		s->index = qb->index;
		r->next = s;
		r = s;
		qb = qb->next;
	}
	r->next = NULL;
	return(head);
}

int main()
{
	polynomial a,b;            //创建两个多项式
	Initpolynomial(a);
	Createpolynomial(a,1.0,1);
	Createpolynomial(a,2.0,2);
	Createpolynomial(a,2.0,3);
	Createpolynomial(a,3.0,4);
	Initpolynomial(b);
	Createpolynomial(b,3.0,1);
	Createpolynomial(b,4.0,2);
	Createpolynomial(b,5.0,5);
	printf("多项式a\n");
	showpolynomial(a);
	printf("多项式b\n");
	showpolynomial(b);

	polynomial c;
	c = Addpolymial(a,b);
	printf("相加后\n");
	showpolynomial(c);
	getchar();
}
怎么说呢 关于这个吧我觉得主要是多熟悉 关键部分是整合代码

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