c语言:多项式相加的实现

#include<iostream>
#include<stdio.h>
#include<math.h>
#define NULL 0
#define LEN sizeof(struct ADD)
using namespace std;
struct ADD            //定义结构体
{
	float xishu;      //数据域
	int zhishu;
    struct ADD *next;  //指针域
}; 
void Initadd(ADD L)   //单链表初始化函数
{
	L.xishu = 0;
	L.zhishu = 0;
	L.next = NULL;
}
struct ADD *Creatadd(void)   //前插法创建单链表
{
	struct ADD *head,*p, *q;
	int n = 0;
	p = (struct ADD*)malloc(LEN);
	q = p;
	cin >> p->xishu >> p->zhishu;
	head= NULL;
	while (p->xishu!=0)
	{
		n++;
		if (n == 1) head = p;
		else q->next = p;
		q = p;
		p = (struct ADD*)malloc(LEN);
		cin >> p->xishu >> p->zhishu;
	}
	q->next = NULL;
	return head;
};
void ADDadd(struct ADD &p1,struct ADD &p2) //相加函数
{
   struct ADD *a,*b,*c,*d;
   a = &p1;    //指针a指向p1
   b = &p2;    //指针b指向p2
	c = a;      //指针c指向指针a
	while (a&&b)
	{
		if (a->zhishu < b->zhishu)       
		{
			c = a;
			a = a->next;   
		}
		else if (a->zhishu > b->zhishu)
		{
			d = b->next;
			b->next = a;
			c->next = b;
			c = a;
			b = d;
		}
		else
		{
			a->xishu = a->xishu + b->xishu;
			if (a->xishu == 0)
			{
				c->next = a->next;
				delete a;
			}
			else
				c = a;
				a = c->next;
				d = b;
				b = b->next;
				delete d;
		}
	}
	if (b)   //如果b->next!=NULL,将b以后的链到c后
		c->next = b;
	    delete b;
}

void printADD(struct ADD &L )    //输出函数
{    
	struct ADD *p = &L;
	while (p != NULL)
	{
		cout << " " << p->xishu << " " << p->zhishu << " ";
		p = p->next;
	}
	cout << endl;
}

int main()
{
 	ADD *head1, *head2;
	cout << "请输入第一个多项式A(x)(默认输入为系数 质数)" <<endl;
	head1=Creatadd();
	cout << "该多项式为A(x)=" << endl;
	printADD(*head1);
	cout << "请输入第二个多项式B(x)(默认输入为系数 质数)" << endl;
	head2=Creatadd();
	cout << "该多项式为B(x)=" << endl; 
	printADD(*head2);
	cout << "多项式的和为A(x)=A(x)+B(x)=(默认输出为系数 质数)" << endl;
	ADDadd(*head1, *head2);
	printADD(*head1);
	return 0;
}

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