双结构多项式链表及其问题

polynomial linked list with two structs and its problems

本文关键字:问题 链表 结构 多项式      更新时间:2023-10-16
#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;
}

这段代码使用链表来存储多项式。一个结构用于多项式度和系数;另一个结构体是用来创建一个Node来创建一个链表。

我的代码有两个问题:

  1. 一个空的多项式,它是NULL,但在构造函数中我的条件语句没有找到它

  2. 为什么我的打印方法不工作

我在打印方法中有这个问题

在多项式.exe中的0x00c1166b处未处理异常:0xC0000005:访问违反读取位置0xcccccccc.

poly == NULL不是true的原因是poly未初始化。初始化poly(NULL)只发生在另一个构造函数中,它没有被使用。

可能最好是消除list类型,而使用std::list(实际上,将listusing namespace std;结合使用是一个非常糟糕的主意)。

class polynomial
{
private:
    list< Term > poly;

现在poly是默认构造的,所以poly->empty()true,你不需要做任何事情。

对于cons,可以调用list::push_backlist::insert;列表的一般格式是list::splice。要对列表进行迭代,可以在list< Term >::iterator类型的对象上使用++操作符。