繁体   English   中英

有两个结构的多项式链表及其问题

[英]polynomial linked list with two structs and its problems

#include <iostream>
using namespace std;
struct Term;
struct Node;

typedef Term* termPtr;
typedef Node* list;

list cons(int degree,int coeff, list p);

struct Term
{
    int degree;
    int coeff;
};

struct Node
{
    termPtr term;
    list link;
};
class polynomial
{
private:
    list poly;
static const int VARIABLE_X='X';
char variable;
public:
    polynomial():poly(NULL),variable(VARIABLE_X){};
    polynomial(int coef,int deg);
    polynomial insert (termPtr t,list p);
    int degree() const;
    int coeff(int n) const;
    void setPrintVariable (char x){variable=x;}
    char getPrintVariable()const { return variable;}
    friend const polynomial readPoly();
    friend void printPoly(polynomial a);
    void deletePoly();
    friend const polynomial operator +(const polynomial &a,const polynomial &b);
    friend const polynomial operator *(const polynomial &a,const polynomial &b);
 };

 polynomial::polynomial(int c,int d)
 {
if(poly == NULL)//compiler doesnt understand this part
    poly = cons(c,d,poly);
    else // i put my cons here just to make the poly
            poly=cons(c,d,poly);

}
list cons(int c,int d, list p)
{
    termPtr aterm = new Term;
    aterm->coeff=c;
    aterm->degree=d;
    list q = new Node;
    q->term = aterm;
    q->link = p;
    return q;
} 

void printPoly (polynomial a)
{
cout<<"[";
if(a.poly == NULL)
    cout<<"]";
else
    while(a.poly != NULL)
    {
        cout<<"("<<a.poly->term->coeff<<" X "<<a.poly->term->degree;
        a.poly=a.poly->link ; 
    }
cout<<endl;
}

此代码使用链接列表存储多项式。 一种结构是多项式的度数和系数。 另一个结构是用于创建节点以创建链接列表。

我的代码有两个问题:

  1. 一个空多项式,它为NULL,但是在构造函数中,我的condition语句找不到它。

  2. 为什么我的打印方法不起作用。

我在打印方法中有此问题

polynomial.exe中0x00c1166b处未处理的异常:0xC0000005:访问冲突读取位置0xcccccccc。

poly == NULLtrue的原因是poly未初始化。 初始化poly(NULL)仅在其他构造函数中发生,而未使用。

可能最好是用std::list消除list类型(实际上,结合使用list作为标识符和using namespace std;是一个非常糟糕的主意)。

class polynomial
{
private:
    list< Term > poly;

现在poly是默认构造的,因此poly->empty()true ,您无需执行任何操作。

对于cons您可以调用list::push_backlist::insert ; 列表的一般分类是list::splice 要遍历列表,请在list< Term >::iterator类型的对象上使用++运算符。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM