Roger M
Roger M

Reputation: 107

C: Circular Linked List - Add Term To Polynomial

I am new to circular linked list and I still have some problems with it... I'm trying to make this function in C, in which given a polynomial and two variables (which are e = exponent of x; and c = coefficient) it will add this cx^e to the polynomial. But it has couple of conditions:

  1. The polynomial must be in ascending order
  2. If there is a term with the same exponent, you should add the terms and not create another one.
  3. You must use a circular linked list, in which its exponents will be the 'headers' of each term.
  4. The first term of each polynomial will be of expo = -1, which will be pointing to the second term of the polynomial (expo >= 0) .Also the last term of the polynomial will be pointing to the first term.

I already tried to make this code, but for some reason I don't know, it is compiling with no problem, but it keeps running forever (and it does not give a segmentation fault or anything like that).

Could you guys, please, tell me what I am doing wrong? I really need your help. Sorry, I know it might be a noob thing, but please be patient, I'm pretty new to this.

typedef struct Term {
  int expo;
  float coef;
  struct Termo *next; 
 } Term, *Polynomial;


void AddTerm(Polynomial p, int e, float c) { 
/* Add in polynomial 'p' the term '(e,c)', leaving the terms in ascending order */
/* Assume that all c will be different than zero. */
    Polynomial rook, save, term;
    rook = p;

    while(rook -> expo < e){
        save = rook;
        rook = rook -> next;
    }

    term = malloc(sizeof(Term));


    if(rook -> expo == e){
        rook -> coef = rook -> coef + c;
    }
    else{
        term -> expo = e;
        term -> coef = c;
        term -> next = save -> next;
        save -> next = term;
    }

} /* AddTerm */

Any help will be greatly appreciated. I'm running on Linux Mint 17 Cinnammon.

Upvotes: 1

Views: 1192

Answers (1)

pat
pat

Reputation: 12749

The initial list contains a single Term with expo = -1, and next pointing back to itself. The while loop is looking for the first Term with expo greater-or-equal to the e you are trying to add; however, at this point, there is no such Term, so the while loop will spin around the circular list forever. You need the loop to terminate when rook comes back around to p.

Once you are out of the loop, you only need to allocate a new Term if you intend to add it to the list. In the case where rook->expo == e, you don't need a new Term.

Upvotes: 1

Related Questions