1. 程式人生 > >【C++】多項式求和,連結串列實現

【C++】多項式求和,連結串列實現

#include<iostream>
using namespace std;
struct node         //建立結構體,包含係數,指數,指標 
{
	int n;
	float c;
	node *next;
};
node *create(char M )      //建立連結串列,存放多項式
{
	int n=0;
	float c=0;
	node *head=NULL,*p1=NULL,*p2=NULL;
	
	cout<<"請按指數升序輸入多項式"<< M <<"的係數,以回車結束:";
	do 
	{	
	    cin>>c;
		if(c)                             //存放係數不為零的項 
		{
			p1=new node;
			p1->c=c;
	        p1->n=n;			
	        if (head==NULL) head=p1;
    	    else p2->next=p1;
            p2=p1;
			p1->next=NULL;
		}
	    n++; 
	}while(cin.get()!='\n');
	
	return head;                 //返回頭指標 
}
node *fun(node *A ,node *B)       //多項式求和 
{
	int n; 
	node *p=NULL,*q=NULL,*head;   //用於標記A的上一個節點
    head=A ;                      //標記頭節點 
	                 
	while(A!=NULL&&B!=NULL)      //逐項比較直到一個多項式結束 
	{
		
		if(A->n - B->n==0)
		{
			A->c=A->c+B->c ;            //同冪指數相加
			if(A->c) p = A ;            //若和非零,保留A地址
			else                        //否則刪去此項 
			{
				if(p!=NULL) {p->next = A->next ; A = A->next;}
				else  {head=A->next;}
			}
			A = A->next;                //AB向後一項移動 
			B = B->next ;	
		}
		else if(A->n - B->n<0) 
		{
			p = A ; A = A->next;    //保留A地址,A向下一項 
		} 
		else
		{
			if(p == NULL)
			{
				q=B->next ;          //儲存B->next 
				B->next= A ;         //將B插至A前 
				head = B;            //頭節點變為B 
				p=A ;B =q;           //保留A地址,B向下一項 
			}
			else 
			{
		     	p->next = B ;        //將B插至A前 
				B->next = A ;        
				B = B->next ;	     //B向下一項 
			}
		}      
	}
	if(A==NULL) p->next = B;          //A結束,將B剩餘項複製至A尾 
	return head;
}
void print(node *head)                //輸出函式 
{
	node *p;
	p=head;
	for(;head!=NULL;head=head->next)
	{
		if(head==p) cout<<head->c;
		else if(head!=p)
    		{
    			if(head->c>0&&head->c!=1) cout<<"+"<<head->c;
    			if(head->c==1) cout<<"+";
			    if(head->c<0&&head->c!=-1) cout<<head->c;
			    if(head->c==-1) cout<<"-";
    		}
		if(head->n!=0) cout<<"x";
		if(head->n!=1&&head->n!=0) cout<<"^"<<head->n;
	}
}
int main()
{
	char A='A' ,B='B';
	node *head1,*head2,*result;
	
	head1=create(A);
	head2=create(B);
	result=fun(head1,head2); 

	cout<<"求和結果為:"<<endl;
	print(result); 
	
	return 0;
}