|
From: <or...@vp...> - 2002-11-19 15:24:37
|
Hello j b!
Monday, November 18, 2002, 8:16:12 PM, you wrote:
jb> i tried to write a code using linked lists to implement the
jb> multiplication and addition of twp polynomials but it seems i'm
jb> not very successfull cause my pop funcition doesn't do what it
jb> should and i don't know why i get that access violation error
jb> ..could any one help??
> /* definitions*/
>
> typedef struct node{
> int coefficient;
> int exponent;
> struct node *next;
> }node;
>
> typedef struct stack{
> node *firstptr;
> }stack;
>
> /*and the pop function*/
>
> node *pop(stack *s){
> node *nptr=new node;
> if(nptr==NULL){
> cout<<"exhausted memory"<<endl;
> exit(1);
> }
> else{
> nptr->coefficient=s->firstptr->coefficient;
> nptr->exponent=s->firstptr->exponent;
> s->firstptr=s->firstptr->next;//that's the problematic part
> }
> return nptr;
> }
Well the above code shouldn't give an access violation error, IF the
push (I assume you have a function named like that) works fine. So I
think the problem is with the push function.
And one more thing. I don't know much about C++, but I'm good at C,
and I think you should clean up memory when you detatch a node from
the list.
Something like:
node *pop(stack *s){
node *ntmp; /* Temporary pointer */
...
else{
...
ntmp = s->firstptr; /*!*/
s->firstptr=s->firstptr->next; //that's the problematic part
free(ntmp); /*!*/
}
return nprt;
}
OR:
===
Why not return only a pointer to the node, instead of creating a new
one?
Then the code would be:
node *pop(stack *s){
node *nptr; /* Only a pointer */
nptr = s->firstptr;
s->firstptr=s->firstptr->next;
return nptr;
}
Of course you will need to free the node that you get, from the
outside.
As I stated above, I don't know much about C++, but I've heard, that
there are many built-in functions, and "things" inside C++ for list
creation. (They are created through templates, as I remember). Look in
the book.
--
Best regards,
Oroszi Balázs mailto:or...@vp...
PGP-FP: FB80 8A43 2664 6126 E465 46E2 2546 CFA3 C25B 9F70
finger -l or...@se...
|