1. 程式人生 > >線性結構應用之多項式相加

線性結構應用之多項式相加

  1. 儲存結構
typedef struct node
{
	int coef;
	int expon;
	struct node* next;
}polyN;
  1. 建立無頭結點的連結串列
polyN* creatPoly()
{
	polyN* p=(polyN*)malloc(sizeof(node));
	p=NULL;
	return p;
}
  1. 新增結點(頭插法)
void add(polyN** p,int c,int e)
{
	polyN* New=(polyN*)malloc(sizeof(node));
	New-
>coef=c; New->expon=e; New->next=*p; *p=New; }
  1. 加法運算
void attach(int c,int e,polyN** rear)//尾插
{
	polyN* New=(polyN*)malloc(sizeof(node));
	New->coef=c;
	New->expon=e;
	New->next=NULL;
	(*rear)->next=New;
	(*rear)=New;
}
polyN* PolyAdd(polyN* p1,polyN* p2)
{
	polyN* rear=
(polyN*)malloc(sizeof(node)); polyN* front=rear; while(p1 && p2) { if(p1->expon>p2->expon){ attach(p1->coef,p1->expon,&rear); p1=p1->next; }else if(p1->expon<p2->expon){ attach(p2->coef,p2->expon,&rear); p2=p2->next; }else{ attach
(p2->coef+p1->coef,p1->expon,&rear); p1=p1->next; p2=p2->next; } } while(p1){ attach(p1->coef,p1->expon,&rear); p1=p1->next; } while(p2){ attach(p2->coef,p2->expon,&rear); p2=p2->next; } rear->next=NULL; polyN* t=front; front=front->next; free(t); return front; }