单链表的应用——多项式加法的C语言实现(链式存储结构)

#include
#include

typedef struct PolyNode{
	int coef;
	int expon;
	struct PolyNode *next;
} *Polynomial;

Polynomial InitPolynomial();
void TraverseList(Polynomial l);
void CreatePolynomial(Polynomial l);
Polynomial PolyAdd(Polynomial p1, Polynomial p2);
Polynomial attach(int coef, int expon, Polynomial p);//

void main()
{
	Polynomial p1, p2, p;

	p1 = InitPolynomial();
	CreatePolynomial(p1);
	p2 = InitPolynomial();
	CreatePolynomial(p2);
	//TraverseList(p1);
	//TraverseList(p2);

	p = PolyAdd(p1, p2);
	p = p->next;//结果多项式p中有头结点,在打印元素时需要跳过头结点。
	TraverseList(p);
}

//初始化多项式(即分配一个内存空间 因为多项式中并不含头结点,所以插入数据时要先使用该内存空间)
Polynomial InitPolynomial()
{
	Polynomial p;
	p = (Polynomial)malloc(sizeof(PolyNode));

	if (!p)
	{
		printf("初始化失败");
		exit(1);
	}
	p->next = NULL;
	return p;
}

//遍历函数 
void TraverseList(Polynomial l)
{
	Polynomial r = l;
	printf("多项式中的元素依次为:");
	while (l)
	{
		printf("系数:%d,指数:%d  ", l->coef, l->expon);
		l = l->next;
	}
	printf("\n");
}

//尾插法创建多项式(链表中无头结点,按幂次递减的顺序排列)
void CreatePolynomial(Polynomial l)
{
	int i, n;
	Polynomial p, r = l;

	printf("请输入多项式的项数:");
	scanf_s("%d", &n);

	printf("请输入多项式的系数和指数(按幂次递减的顺序):");
	scanf_s("%d,%d", &l->coef, &l->expon);
	for (i = 1; i < n; i++)
	{
		p = (Polynomial)malloc(sizeof(PolyNode));
		printf("请输入多项式的系数和指数(按幂次递减的顺序):");
		scanf_s("%d,%d", &p->coef, &p->expon);
		r->next = p;
		r = p;
	}
	r->next = NULL;
}

Polynomial PolyAdd(Polynomial p1, Polynomial p2)
{
	int coef;
	Polynomial r, p;
	//初始化链表r
	p = (Polynomial)malloc(sizeof(PolyNode));
	p->next = NULL;
	r = p;

	while (p1 && p2)
	{
		if (p1->expon == p2->expon)
		{
			coef = p1->coef + p2->coef;
			if (coef)
				p = attach(coef, p1->expon, p);
			p1 = p1->next;
			p2 = p2->next;
		}
		else if (p1->expon > p2->expon)
		{
			p = attach(p1->coef, p1->expon, p);
			p1 = p1->next;
		}
		else
		{
			p = attach(p2->coef, p2->expon, p);
			p2 = p2->next;
		}
	}
	//将未处理完的另一个多项式的所有节点依次复制到结果多项式中去
	for (; p1; p1 = p1->next) p = attach(p1->coef, p1->expon, p);
	for (; p2; p2 = p2->next) p = attach(p2->coef, p2->expon, p);
	return r;
}

//尾插法添加数据(注意p链表中含有头结点)
Polynomial attach(int coef, int expon, Polynomial p)
{
	Polynomial r;

	r = (Polynomial)malloc(sizeof(PolyNode));
	r->coef = coef;
	r->expon = expon;
	r->next = p->next;
	p->next = r;
	p = r;
	return p;
}

测试结果:

单链表的应用——多项式加法的C语言实现(链式存储结构)_第1张图片

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