循环链表分配运算符

时间:2017-04-05 22:32:08

标签: c++

我需要在循环链表上实现赋值运算符=这里是结构和我的代码到目前为止。但我不知道如何复制系数和功率

struct Term {                             // a term on the sparce polynomial

    double coeff;                         // the coefficient of each term

    int power;                                    // the degree of each term

    Term *prev;                     // a pointer to the previous higher term
    Term *next;                          // a pointer to the next lower term
};
int size;                               // # terms in the sparce polynomial
Term *head;               // a pointer to the doubly-linked circular list of

Polynomial& Polynomial::operator=(const Polynomial &rightpoly){

 // check for self assignment
 if(&rightpoly !=this){
     // clear this
     if(head !=NULL)
         delete this;
     if(rightpoly.head == NULL)
         return *this;
     // make new node for the head
     Term *ptr = new Term;

     head = ptr;
     Term *curRight = rightpoly.head ->next;
     Term *curLeft = ptr;

     // traverse the list, making a new node and copying data
     // until rightpoly is empty
     while (curRight !=NULL) {
         curLeft ->next = new Term;
         curLeft = curLeft ->next;
         curRight = curRight ->next;
     }
     curLeft ->next = NULL;
 }
 return *this;
}

0 个答案:

没有答案