Reputation: 107
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:
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
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