chirag said:
hi i am writing the following function . but does not seem to put the code
in sequence. it does not compile. its kind of messed up. please help me
improve it. thanks.
void addToEndOfLinkedList(Node * &head)
Just pass the pointer, no need to pass it by reference.
Is this argument a new node or a pointer to the start of the list?
// 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();
while ((cin >> a) && (a != -1))
if (prev==NULL)
{
Node *newPtr;
Node *newvalue;
newPtr = new Node;
newPtr->item= newvalue;
newPtr->next = NULL;
NULL= newPtr;
}
}
Rather than correct your code, here is the generic
code for appending a node to a list:
struct Node
{
Node * next;
};
struct Integer_Node
: public Node
{
int value;
};
void Append_To_List(Node * &list_start,
Node * new_node)
{
/* Make sure that the pointer to the new node is
* not NULL. Bad things happen when dereferencing
* a NULL pointer.
*/
assert(new_node != NULL);
/* As a precaution, set the "next" field of the
* new node to NULL. This may not be necessary,
* but better safe than sorry.
*/
new_node->next = NULL;
if (list_start == NULL)
{
// This is the reason for passing the pointer
// by reference.
list_start = new_node;
}
else
{
Node * prev = list_start;
Node * n = list_start;
/* Search for the end of the list, and maintain
* a pointer to the previous node.
*/
while (n != NULL)
{
prev = n;
n = n->next;
}
/* At this point, "prev" points to the last node
* in the list. Link the new node to the "prev"
* node.
*/
prev->next = n;
}
return;
}
The above function only appends a node to the list.
The creating of a node has been extracted to make
the functionality more generic so it can be used for
programs that create nodes from files, databases, etc,
not just from cin.
Also note that the above function only deals with the
link field and not the value field. That is why I have
separated the two fields into separate classes.
int main(void)
{
Integer_Node * list_head;
Integer_Node * i_node;
cout<<"Enter an integer, -1 to quit:";
cout.flush();
int a;
while ((cin >> a) && (a != -1))
{
i_node = new Integer_Node;
i_node->value = a;
Append_To_List(list_head, i_node);
cout<<"Enter an integer, -1 to quit:";
cout.flush();
}
return 0;
}
--
Thomas Matthews
C++ newsgroup welcome message:
http://www.slack.net/~shiva/welcome.txt
C++ Faq:
http://www.parashift.com/c++-faq-lite
C Faq:
http://www.eskimo.com/~scs/c-faq/top.html
alt.comp.lang.learn.c-c++ faq:
http://www.comeaucomputing.com/learn/faq/
Other sites:
http://www.josuttis.com -- C++ STL Library book
http://www.sgi.com/tech/stl -- Standard Template Library