C++/add node to the last link list in C++; needs help
Expert: Zlatko - 2/21/2010
QuestionThis program actually have 4 function.
1)AddLast = to add a new node at the last of the list
2)FindNode = to find the desired node
3)DeleteNode = to delete the desired node
4)DisplayNode = display the list
Now..my problems is with the AddLast function..
Before this I done with the AddFirst..Therefore,i try for this AddLast fuction.
I have already compile it using DevC compiler..no error listed..
But suddenly when the command prompt ask me to close the program..
I think maybe it became crash..Why???
I think the AddLast function is correct..
So,,can anyone help me to fix this crash things so that I can compile&run this code..
class List
{
public:
List(void) { head = NULL; } // constructor
~List(void); // destructor
bool IsEmpty() { return head == NULL; }
Node* AddLast(int index, double x);
int FindNode(double x);
int DeleteNode(double x);
void DisplayList(void);
private:
Node* head;
};
Node* List::AddLast(int index,double x) //please check for me with this AddLast function
{
if(index<0)
return NULL;
Node* currNode=head;
Node* newNode = new Node;
newNode->data = x;
if(head == NULL)
head = newNode;
else
{
currNode->next = head;
while(currNode->next !=NULL)
{
currNode = currNode->next;
}
currNode->next = newNode;
}
}
int main()
{
List n;
n.AddLast(22,7.0);
n.AddLast(44,5.0);
n.AddLast(66,3.0);
n.AddLast(88,6.0);
n.AddLast(99,4.0);
n.DisplayList();
}
AnswerHello wale89
Please make sure that your Node constructor sets the Node::next pointer to NULL. You did not supply me with all the code so I can only guess at what Node looks like. Here is my version of Node
struct Node
{
Node() {next = NULL;}
Node* next;
double data;
};
In List::AddLast you do not need an index parameter. What purpose would it serve ? Also the AddLast does not return anything, so declare it as void.
The biggest problem is the line currNode->next = head, right before the loop while(currNode->next !=NULL)
That line causes head to point to itself and you get an unending loop.
Here is a working version of your code.
Best regards
Zlatko
#include <stdlib.h>
struct Node
{
Node() {next = NULL;}
Node* next;
double data;
};
class List
{
public:
List(void) { head = NULL; } // constructor
void AddLast(double x);
private:
Node* head;
};
void List::AddLast(double x) //please check for me with this AddLast function
{
Node* currNode=head;
Node* newNode = new Node;
newNode->data = x;
if(head == NULL)
{
head = newNode;
}
else
{
//XXX this is the problem ->>>>> currNode->next = head;
while(currNode->next !=NULL)
{
currNode = currNode->next;
}
currNode->next = newNode;
}
return;
}
int main()
{
List n;
n.AddLast(7.0);
n.AddLast(5.0);
n.AddLast(3.0);
n.AddLast(6.0);
n.AddLast(4.0);
//n.DisplayList();
return 0;
}