多项式加法 链表方法

#include <iostream>
#include <stdlib.h>

using namespace std;

struct item
{
    int a;
    int m;
    struct item *next;
};
 
item *node1()
{
    item *p=NULL;
    item *q=NULL;
    item *first=NULL;
    first=NULL;
    int A;
    cout<<"请输入node1的多项式:"<<endl;
    cout<<"请输入a的值:";
    cin>>A;
    while(A!=0)
    {
        p=new item;
        p->a=A;
        cout<<"请输入m的值:";
        cin>>p->m;
        if(first==NULL)
        first=p;
        else
        q->next=p;
        q=p;
        cout<<"请输入a的值:";
        cin>>A;
    }
        q->next=NULL;
        return (first);
}

 

item *node2()
{
    item *r=NULL;
    item *l=NULL;
    item *second=NULL;
    second=NULL;
    int B;
    cout<<"请输入多项式node2的项:"<<endl;
    cout<<"请输入a的值:";
    cin>>B;
    while(B!=0)
    {
        r=new item;
        r->a=B;
        cout<<"请输入m的值:";
        cin>>r->m;
        if(second==NULL)
        second=r;
        else
        l->next=r;
        l=r;
        cout<<"请输入a的值:";
        cin>>B;
    }
        l->next=NULL;
        return (second);
}

item *insert(item *mode1,item *mode2)
{
    item *k=NULL;
    item *n=NULL;
    item *s=NULL;
    item *t=NULL;
    item *first=mode1;
    item *second=mode2;
    k=first;
    s=first;
    n=second;
    t=second;
    while (n->next!=NULL)
    {
        while(k->m > n->m)
        {
            s=k;
            k=k->next;
        }
        t=n;
        if(k->m==n->m)
        k->a=(k->a+n->a);
        else
       {
           n->next=k;
           s->next=n;
       }
      t=t->next;
      n=t;
  }
     if(k->m > n->m)
     {
         n->next=k;
         s->next=n;
     }
     else if(k->m==n->m)
     k->a=n->a+k->a;
     else
    {
         while(k->m<n->m)
         {
              s=k;
              k->next;
         }
              if(k->m=n->m)
              k->a=k->a+n->a;
              else
        {
              n->next=k;
              s->next=n;
        }
    }
    first=mode1;
    return(first);  
}

item print(item *head)
{
    while(head!=NULL)
    {
        cout<<head->a<<endl;
        cout<<head->m<<endl;
        head=head->next;
    }
}
int main(int argc, char *argv[])
{
  print(insert(node1,node2));
  system("PAUSE"); 
  return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值