一元多项式求和(c++源码)

LinkList.h

#ifndef LINKLIST_H_
#define LINKLIST_H_
#include<stdio.h>
template<class T>
struct Node
{
    T data;
    struct Node<T>* next;
};
template<class T>
class LinkList
{
private:
    Node<T>* front;
public:
    LinkList();
    LinkList(T data[],int n);
    ~LinkList();
    Node<T>* GetFirst(){return front;}
};
template<class T>
LinkList<T>::LinkList()
{
    front=new Node<T>;
    front->next=NULL;
}
template<class T>
LinkList<T>::LinkList(T data[],int n)
{
    front=new Node<T>;
    front->next=NULL;
    for(int i=n-1;i>=0;i--)
    {
        Node<T>* s=new Node<T>;
        s->data=data[i];
        s->next=front->next;
        front->next=s;
    }
}
template<class T>
LinkList<T>::~LinkList()
{
    Node<T>* p=front;
    while(p)
    {
        front=p;
        p=p->next;
        delete front;
    }
}
#endif // LINKLIST_H_

Element.h

#ifndef ELEMENT_H_
#define ELEMENT_H_
#include<iostream>
#include"LinkList.h"
#include<stdio.h>
struct element
{
    double xs;
    int zs;
    element(double x=0,int z=0):xs(x),zs(z){}
};
class PloyList:public LinkList<element>
{
public:
    PloyList(element data[],int n):LinkList(data,n){}
    void Add(PloyList& B);
    void Print();
};
void PloyList::Add(PloyList& B)
{
    Node<element>* pa=GetFirst();
    Node<element>* pb=B.GetFirst();
    Node<element>* p=pa->next;
    Node<element>* q=pb->next;
    while(p&&q)
    {
        if(q->data.zs>p->data.zs)
        {
            pa=p;
            p=p->next;
        }
        else if(q->data.zs<p->data.zs)
        {
            pa->next=q;
            pa=q;
            q=q->next;
            pa->next=p;
        }
        else
        {
            p->data.xs+=q->data.xs;
            if(p->data.xs==0)
            {
                pa->next=p->next;
                delete p;
                p=pa->next;
            }
            else
            {
                pa=p;
                p=p->next;
            }
            Node<element>* temp=q;
            q=q->next;
            delete temp;
        }
    }
    if(q)pa->next=q;
    B.GetFirst()->next=NULL;
}
void PloyList::Print()
{
    Node<element>* p=GetFirst()->next;
    while(p)
    {
        std::cout<<"("<<p->data.xs<<", "<<p->data.zs<<") ";
        p=p->next;
    }
    std::cout<<std::endl;
}
#endif // ELEMENT_H_

Use.cpp

#include<iostream>
#include"Element.h"
int main()
{
    element ea[]={element(1,0),element(2.3,2),element(3,4)};
    element eb[]={element(1,1),element(-2.3,2),element(3,4),element(5,10)};
    PloyList a(ea,3),b(eb,4);
    a.Add(b);
    a.Print();
    return 0;
}
©️2020 CSDN 皮肤主题: 岁月 设计师:pinMode 返回首页