Re: how to add at the end of the linked list
From: Rolf Magnus (ramagnus_at_t-online.de)
Date: 02/11/05
- Next message: Rufus V. Smith: "Re: Google-groups indentation problem fixed!!!!"
- Previous message: chirag: "how to add at the end of the linked list"
- In reply to: chirag: "how to add at the end of the linked list"
- Next in thread: Thomas Matthews: "Re: how to add at the end of the linked list"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Date: Fri, 11 Feb 2005 19:14:55 +0100
chirag wrote:
> hi i am writing the following function . but does not seem to put the code
> in sequence. it does not compile.
And no error message form the compiler?
> its kind of messed up. please help me improve it. thanks.
>
> void addToEndOfLinkedList(Node * &head)
Why do you pass the pointer by reference? You are not writing to it.
Actually, you aren't using the pointer at all in the function.
> // Reads a series of integers from the keyboard (ending with -1) and
> // appends them to the end of the linked list pointed to by head. No
> // error checking is done. Correctly handles the case when the
> // original list starts out empty.
>
> {
>
> int a;
> int prev;
>
> cout<<"Enter an integer, -1 to quit:";
> cout.flush();
No need to flush here. cin and cout are tied together, which means that
reading from cin will automatically flush cout.
> while ((cin >> a) && (a != -1))
You're reading your integers here, but you are never using them for anything
except ending the loop.
> if (prev==NULL)
prev is uninitialized. Don't ever use variables that haven't been
initialized and haven't been written to before. The value is undefined.
Another thing: Never use NULL in an integer context. It is meant for
pointers only. Actually, it's a good idea to not use NULL at all. Just use
0. Anyway, I'm not sure that prev actually is supposed to be an integer.
What is the purpose of prev?
> {
> Node *newPtr;
> Node *newvalue;
>
> newPtr = new Node;
> newPtr->item= newvalue;
Again, newvalue is uninitialized. Also, is newPtr->item really a pointer to
Node? Looks to me as if you actually should assign the variable a to it.
> newPtr->next = NULL;
> NULL= newPtr;
That last assignment makes no sense. You cannot assign anything to NULL.
What was the intention of that?
Where are you actually appending your new node to the list?
> }
> }
- Next message: Rufus V. Smith: "Re: Google-groups indentation problem fixed!!!!"
- Previous message: chirag: "how to add at the end of the linked list"
- In reply to: chirag: "how to add at the end of the linked list"
- Next in thread: Thomas Matthews: "Re: how to add at the end of the linked list"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Relevant Pages
|