Hi . I want Add a Node To End List But my Program in during compile time Terminated . what is my fault ?
#include<iostream>
using namespace std;
class Node
{
public:
Node();
void newInsert(Node* );
void endInsert(Node* );
private:
int item;
Node* next;
};
int main()
{
Node* head;
Node *p;
p = new Node;
p->newInsert(head);
p->endInsert(head);
return 0;
}
Node::Node() : item(0), next(NULL)
{
}
void Node::newInsert(Node* head)
{
Node* newPtr;
newPtr = new Node;
cout << " Please Enter Item : ";
cin >> newPtr->item;
newPtr -> next = NULL;
head = newPtr;
}
void Node::endInsert(Node* head)
{
Node* Ptr = new Node;
Node* cur = head;
Node* prev = NULL;
cout << " Pleas Enter Item : ";
cin >> Ptr->item;
while(cur != NULL)
{
prev = cur;
cur = cur -> next;
}
if( cur == NULL)
{
Ptr->next = cur;
prev->next = Ptr;
}
}
I don't see anything wrong with your algorithm. Though the if statement in endInsert is redundant. It doesn't work because your functions don't modify the head pointer, as it is passed by value. I added some debug code so that you can see that head's value doesn't change. I also added (in comments) the changes you have to make to your functions signatures so that it works.