链表问题2——多项式加法

这个以前学数据结构时就学过的,用c++实现起来很顺利,不过提交时超时,改进后虽然也是O(n^2)复杂度,不过还是Accepted。

思路:链表的结点【系数】【指数】【指向下个结点的指针next】;构造链表时结点按指数从大到小的顺序进行插入操作。一开始,我还设置了add函数实现相加,不过参考一个博客发现没必要增加无谓的代码,直接在插入时判断是否存在指数相等的结点,若存在则相加,不存在就插入。

#include<iostream>
using namespace std;

class polyNode
{
public:
    int x;
    int y;
    polyNode* next;
    polyNode(int x=0,int y=9999,polyNode* next=NULL)
    {
        this->x=x;
        this->y=y;
        this->next=next;
    }
};
class poly
{
private:
    polyNode *head;
    int len;
public:
    poly()
    {
        head=new polyNode();
        len=0;
    }
    ~poly()
    {
        polyNode *p=head;
        polyNode *q=p;
        while(p)
        {
            q=p->next;
            delete p;
            p=q;
        }
        len=0;
    }
    int getLen()
    {
        return len;
    }
    void insert(int x,int y)//构造的时候进行相加
    {
        polyNode *p=head;
        polyNode *newNode=new polyNode(x,y);
        while( p->next!=NULL && p->next->y > y) //只有头节点
        {
            p=p->next;
        }
        if(p->next!=NULL && p->next->y == y)
        {
            p->next->x+=x;
        }else{
            newNode->next=p->next;
            p->next=newNode;
            len++;
        }
    }

    //打印多项式
    void print()
    {
        polyNode *p=head->next;
        while(p)
        {
            if(p->x !=0){
            cout<<"[ "<<p->x<<" "<<p->y<<" ] ";
            }
            p=p->next;
        }
        cout<<endl;
    }
    void build(){
        int x,y;
        while(cin>>x>>y&& y>=0 ){
            insert(x,y);
        }
    }

    void add()
    {
        build();
        build();
        print();
    }

};

int main()
{

    int n;
    cin>>n;
    while(n--){
        poly a;
        a.add();
    }
    return 0;
}

  

 

posted @ 2016-06-03 14:24  swu_mqw  阅读(247)  评论(0)    收藏  举报