Aceso
Aceso

Reputation: 1215

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;
}

This code is using linked lists to store polynomials. One struct is for the polynomial degree and coeff; another struct is for making a Node in order to create a linked list.

I have two problems with the code:

  1. An empty polynomial which is NULL but in the constructor my condition statement doesn't find it out.

  2. Why my print method doesn't work.

I have this problem in the print method

Unhandled exception at 0x00c1166b in polynomial.exe: 0xC0000005: Access violation reading location 0xcccccccc.

Upvotes: 0

Views: 1801

Answers (1)

Potatoswatter
Potatoswatter

Reputation: 137770

The reason poly == NULL is not true is that poly is uninitialized. The initialization poly(NULL) only occurs in the other constructor, which is not used.

Probably it is best to eliminate the list type in favor of std::list (actually, it is a very bad idea to use list as an identifier in conjunction with using namespace std;).

class polynomial
{
private:
    list< Term > poly;

Now poly is default-constructed so poly->empty() is true, and you don't have to do anything.

For cons you can call list::push_back or list::insert; general catenation of lists is list::splice. To iterate over the list use the ++ operator on an object of type list< Term >::iterator.

Upvotes: 1

Related Questions