一元函数 第二章 数据结构与算法分析 张琨

yiyuan.h
#ifndef YIYUAN_H_
#define YIYUAN_H_

#define Max 20
typedef struct
{
	float coef;
	int exp;
}PolyArray[Max];

struct PolyNode
{
	float coef;
	int exp;
	PolyNode *next;
};

class Poly
{
private:
	PolyNode *Head;
public:
	Poly();
	~Poly(){}
	void CreatPoly(PolyArray a, int n);
	void PolyDisplay();
	void PolySort();
	void PolyAdd(Poly LB);
	PolyNode *hhh(){ return Head; }
};

#endif
dingyi.cpp
#include"yiyuan.h"
#include
#include
using std::ostream;
using std::endl;

Poly::Poly()
{
	/*PolyNode *Head;*/
	Head = (PolyNode *)malloc(sizeof(PolyNode));
}

void Poly:: CreatPoly(PolyArray a, int n)
{ 
	PolyNode *s, *r;
	//Head = (PolyNode *)malloc(sizeof(PolyNode));
	
	int i;
	r = Head;
	for (i = 0; i < n; i++)
	{
		s = new PolyNode;
		s->coef = a[i].coef;
		s->exp = a[i].exp;
		s->next = nullptr;
		r->next = s;
		r = s;
	}

}

void Poly::PolySort()
{
	/*PolyNode *Head;
	Head = (PolyNode *)malloc(sizeof(PolyNode));*/
	PolyNode *p, *q, *r;
	p = Head->next;
	if (p != nullptr)
	{
		r = p->next;
		p->next = nullptr;
		p = r;
		while (p != nullptr)
		{
			r = p->next;
			q = Head;
			while (q->next != nullptr&&q->next->exp < p->exp)
				q = q->next;
			    p->next = q->next;
			    q->next = p;
			    p = r;
		}
	}

}


void Poly::PolyAdd(Poly LB)
{
	/*PolyNode *Head;
	Head = (PolyNode *)malloc(sizeof(PolyNode));*/
	float sum;
	PolyNode *pa, *pb, *qa, *qb;
	pa = Head;
	qa = pa->next;
	pb = LB.hhh();
	qb = pb->next;
	while (qa != nullptr&& qb != nullptr)
	{
		if (qa->exp < qb->exp)
		{
			pa = qa; qa = qa->next;
		}

		else if (qa->exp > qb->exp)
		{
			pb->next = qb->next;
			qb->next = qa;
			pa->next = qb;
			pa = qb;
			qb = pb->next;

		}
		else
		{
			sum = qa->coef + qb->coef;
			if (sum == 0)
			{
				pa->next = qa->next;
				delete qa;
				qa = pa->next;
				pb->next = qb->next;
				delete qb;
				qb = pb->next;
			}
			else
			{
				qa->coef = sum;
				pa = qa; qa = qa->next;
				pb->next = qb->next;
				delete qb;
				qb = pb->next;
			}
		}
		
	}
	if (qb != nullptr)
	{
		pa->next = qb;
	}
}

void Poly::PolyDisplay()
{
	PolyNode *x;
	x = Head->next;
	while (x!=nullptr)
	{
	std::cout << x->coef << "and" << x->exp<next;
	}

}


 
  
源.cpp
#include
#include"yiyuan.h"


void main()
{
	Poly LA, LB;
	PolyArray a = { { 7.0, 0 }, { 3.0, 1 }, { 9.0, 8 }, { 5.0, 16 } };
	PolyArray b = { { 8.0, 1 }, { 22, 7 }, { -9.0, 8 } };
	LA.CreatPoly(a, 4);
	LB.CreatPoly(b, 3);
	LA.PolySort();
	LB.PolySort();
	LA.PolyAdd(LB);
	LA.PolyDisplay();
}

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