zoukankan      html  css  js  c++  java
  • 数据结构之一元多项式加法(C++版)

    #include <iostream>
    #include <stdlib.h>
    using namespace std;

    typedef struct LNode{
    float coef; //系数
    int expn; //指数
    struct LNode *next; //指针域
    }LNode, *SLink;

    int main()
    {
    //一元多项式加法,输入两个一元多项式La, Lb,输出两个一元多项式的和Lc
    SLink La, Lb, Lc, pa, pb, pc, ra, rb, q;
    int m, n, j;
    cout << "请输入一元多项式La的项数:";
    cin >> m;
    La = new LNode;
    ra = La;
    if(!La) exit(0); //存储空间分配失败
    cout << "依次输入" << m << "个项的系数指数:";
    for(j = 0; j < m; j++)
    {
    pa = new LNode; //生成新节点
    cin >> pa->coef >> pa->expn;
    ra->next = pa; ra = pa; //插入到表头
    }
    ra->next = NULL;
    cout << "请输入一元多项式Lb的项数:";
    cin >> n;
    Lb = new LNode;
    rb = Lb;
    if(!Lb) exit(0); //存储空间分配失败
    cout << "依次输入" << n << "个项的系数指数:";
    for(j = 0; j < n; j++)
    {
    pb = new LNode; //生成新节点
    cin >> pb->coef >> pb->expn;
    rb->next = pb; rb = pb; //插入到表头
    }
    m += n;
    rb->next = NULL;
    pa = La->next; pb = Lb->next; Lc = pc = La; q = Lc->next;
    while(pa && pb) //将pa,pb节点按大小一次插入c中
    {
    if(pa->expn < pb->expn)
    {
    pc->next = pa; pc = pa; pa = pa->next;
    }
    else if(pa->expn > pb->expn)
    {
    pc->next = pb; pc = pb; pb = pb->next;
    }
    else
    {
    pa->coef = pa->coef + pb->coef; pc->next = pa; pc = pa; pa = pa->next; pb = pb->next;
    m--;
    }
    }
    pc->next = pa ? pa : pb;

    delete Lb; //释放Lb头节点
    j = 0;
    cout << "两一元多项式的和: Lc = ";
    while(j < m)
    {
    cout << q->coef << "x^" << q->expn;
    if(j < m - 1)
    cout << " + ";
    q = q->next;
    j++;
    }
    cout << endl;
    }//MergeList_L

  • 相关阅读:
    正敲着代码,鼠标坏了!
    DB2 OLAP函数的使用(转)
    修剪矩形
    classpath和环境变量设置(转)
    MyEclipse断点调试JavaScript浅析(转)
    Onunload和onbeforeunload方法的异同
    db2中的coalesce函数(转)
    db2:根据TABLEID找table
    [转]DB2行列转换
    DB2删除数据时的小技巧
  • 原文地址:https://www.cnblogs.com/wwttsqt/p/7783208.html
Copyright © 2011-2022 走看看