一元多项式的相加

    struct PolyNode
{
	int coef;
	int expon;
	struct PolyNode* link;
};
typedef struct PolyNode* Polynomial;
Polynomial P1, P2,PS;
int Compare(int e1, int e2)
{
	if (e1 > e2)
		return 1;
	else if (e2 < e2)
		return -1;
	else if (e2 == e1)
		return 0;
}
void Attach(int c, int e, Polynomial *PRear)
{
	Polynomial P;
	P = (Polynomial)malloc(sizeof(struct PolyNode));
	P->coef = c;
	P->expon = e;
	P->link = NULL;
	(*PRear)->link = P;
	(*PRear) = P;
}
Polynomial ReadPoly()
{
	Polynomial P,Rear,t;
	int c, e, N;
	printf("请输入有多少项:\n");
	scanf("%d", &N);
	P = (Polynomial)malloc(sizeof(struct PolyNode));
	P->link = NULL;
	Rear = P;
	printf("请输入每一项的系数,和指数用空格隔开:\n");
	while (N--)
	{
		scanf("%d %d", &c, &e);
		Attach(c, e, &Rear);
	}
	t = P; P = P->link; free(t);
	return P;
}

Polynomial Add(Polynomial P1, Polynomial P2)
{
	Polynomial front, rear, temp;
	int sum;
	rear = (Polynomial)malloc(sizeof(struct PolyNode));
	front = rear;
	while (P1&&P2)
	{
		switch (Compare(P1->expon, P2->expon))
		{
		case1:
		  {
			Attach(P1->coef, P1->expon, &rear);
			P1 = P1->link;
			break;
		  }
		case -1:
		  {
			Attach(P2->coef, P2->expon, &rear);
			P2 = P2->link;
			break;
		  }
		case 0:
		  {
				  sum = P1->coef + P2->coef;
				  if (sum)Attach(sum, P1->expon, &rear);
				  P1 = P1->link;
				  P2 = P2->link;
				  break;
		  }
		}
	}
	for (; P1;P1=P1->link)
		Attach(P1->coef,P1->expon,&rear);

	for (; P2;P2=P2->link)
		Attach(P2->coef,P2->expon,&rear);
	rear->link = NULL;
	temp = front;
	front = front->link;
	free(temp);
	return front;
}
void PrintPoly(Polynomial P)
{
	int flag = 0;
	if (!P){ printf("0\n"); return; };
	while (P)
	{
		if (flag == 0)
			flag = 1;
		else
			printf(" ");
		printf("%d %d", P->coef, P->expon);
		P = P->link;
	}
}
int main() 
{   
        P1 = ReadPoly();
	P2 = ReadPoly();
	PS = Add(P1, P2);
	PrintPoly(PS);
        return 0;
}

阅读更多
想对作者说点什么?

博主推荐

换一批

没有更多推荐了,返回首页