Re: linked list help please.
From: B. v Ingen Schenau (bart_at_ingen.ddns.info)
Date: 03/31/04
- Next message: Donald Davidson: "basic i/o question"
- Previous message: Leor Zolman: "Re: Strange Operator"
- In reply to: fighterman: "linked list help please."
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Date: Wed, 31 Mar 2004 19:02:29 +0200
fighterman wrote:
> I have a class
>
> template <typename T>
> class node
> {
> public:
> T nodevalue; //store value
> node<T> *next;
When the current node gets destroyed, who is responsible for destroying the
object pointed to by next?
>
> node(){next=NULL;}
> node( T value, node<T> * ptr = NULL): nodevalue(value),next(ptr)
> {}
> };
>
> this is insertrear function to insert node at the back of the linked list
>
> template <typename T>
> void insertrear( T value, node<T> * ptr)
> {
> node<T> *curr = *ptr;
Are you sure that the code compiles without warnings/errors and that you
copy/pasted the code into the message?
The line above should not compile, because you try to initialise a pointer
to a node<T> with a node<T> object (the object that ptr points to).
> node<T> * temp= new node<T>(value);
>
> if(curr=NULL)
^
This is an assignment, not a test for equality.
> {
>
> temp->next=curr;
> curr=temp;
This assignment does not affect the passed in pointer in any way.
>
> }
> else{
> while(curr->next!=NULL)
> {
>
> curr=curr->next;
> }
>
> temp->next=curr->next;
> curr->next=temp;
> }
>
> delete temp;
Here you destroy the node, whose address you just stored in the list.
> }
>
> And in the main function
>
> int main()
> {
> node<int> *head;
head should point to an existing node, or it should have the value NULL.
> for (int i=9; i>=0; i--)
> insertrear( i , head);
>
> return 0;
> }
>
> the problem is why when i run it, there is an pop up window said debug
> error, run time check #3, head is using without defined.
>
> I think when I declare head it will call the default constructor which is
> next = NULL
head is a _pointer_, so the default constructor for pointers (which does
exactly nothing) is invoked.
Bart v Ingen Schenau
-- a.c.l.l.c-c++ FAQ: http://ma.rtij.nl/acllc-c++.FAQ.html c.l.c FAQ: http://www.eskimo.com/~scs/C-faq/top.html c.l.c++ FAQ: http://www.parashift.com/c++-faq-lite/
- Next message: Donald Davidson: "basic i/o question"
- Previous message: Leor Zolman: "Re: Strange Operator"
- In reply to: fighterman: "linked list help please."
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Relevant Pages
|
|