其他分享
首页 > 其他分享> > DSAAC习题3.6

DSAAC习题3.6

作者:互联网

/*默认header和NULL*/
/*默认数据输入是次数从高到底排序*/
#include <stdio.h>
#include <stdlib.h>

struct node {
	int coef;
	int exp;
	struct node* next;
};
typedef struct node* term;
typedef struct node* poly;

void insert(int c, int e, term p)
{
	term temp = malloc(sizeof(struct node));
	if (temp == NULL)
		Error("no space!");

	temp->coef = c;
	temp->exp = e;
	temp->next = p->next;
	p->next = temp;
}

void move(term x)
{
	x = x->next;
}

poly add_polys(poly p1, poly p2)
{
	term pos1, pos2;
	pos1 = p1->next;
	pos2 = p2->next;
	int c, e;
	poly result = malloc(sizeof(struct node));
	term result_pos=result;
	while (pos1 != NULL && pos2 != NULL)
	{
		if (pos1->exp > pos2->exp)
		{
			c = pos1->coef;
			e = pos1->exp;
			move(pos1);
		}
		else if (pos1->exp < pos2->exp)
		{
			c = pos2->coef;
			e = pos2->exp;
			move(pos2);
		}
		else
		{
			c = pos1->coef + pos2->coef;
			e = pos1->exp;
			move(pos1);
			move(pos2);
		}
		insert(c, e, result_pos);
		move(result_pos);
	}

	while (pos1 == NULL)
	{
		insert(pos2->coef, pos2->exp, result_pos);
		move(result_pos);
	}

	while (pos2 == NULL)
	{
		insert(pos1->coef, pos1->exp, result_pos);
		move(result_pos);
	}

	return result;
}

标签:coef,move,3.6,result,exp,DSAAC,习题,pos2,pos1
来源: https://blog.csdn.net/weixin_43709969/article/details/120450859