AM hoping someone can help me with my code. This is a single linkedlist code.
WHile i start entering my values to build the list, i get a message saying the program has stopped running.. can anyone help me..
# include <iostream>
usingnamespace std;
struct Node
{
int info;
Node* link;
};
class LinkedList
{
private:
Node *first;
Node *last;
int count;
public:
LinkedList();
void insertbeg(int newItem);
void print() ;
void insertend(int newItem);
void deleteNode(int deleteItem);
void buildListForward();
int front() const;
~LinkedList();
void traverse_and_print();
void destroyList();
};
LinkedList::LinkedList()
{
first = last = NULL;
count = 0;
}
void LinkedList::destroyList()
{
Node * temp;
temp = first; //set temp to the current node
first = first->link; //advance first to the next node
delete temp; //deallocate the memory occupied by temp
last = NULL; //initialize last to NULL; first has already been set to NULL by the while loop
count = 0;
}
LinkedList::~LinkedList()
{
destroyList();
}
int LinkedList :: front() const
{
return first->info; //return the info of the first node
}//end
void LinkedList::print()
{
Node * current; //pointer to traverse the list
current = first; //set current point to the first node
while (current != NULL) //while more data to print
{
cout << current->info << " ";
current = current->link;
}
}
void LinkedList::traverse_and_print()
{
Node *p = first;
if (first == NULL)
{
cout << "The list is empty" << endl;
return;
}
cout << "LinkedList: ";
/* A basic way of traversing a linked list */
while (p != NULL)
{ /* while there are some more nodes left ,output the value */
cout << p->info;
p = p->link;
}
cout << endl;
}
/*
int linkedListType :: length()
{
return count;
}
*/
void LinkedList :: insertbeg(int newitem)
{
Node *newNode;
if (first == NULL)
{
newNode->info = newitem;
newNode->link = NULL;
first = newNode;
last = newNode;
}
}
void LinkedList :: insertend(int newitem)
{
Node *newNode;
newNode->info = newitem;
newNode->link = NULL;
last->link = newNode;
last = newNode;
}
void LinkedList :: buildListForward()
{
int num;
cout << "Enter a list of integers ending with -999. "<< endl;
cin >> num;
first = NULL;
while (num != -999)
{
Node *newNode = NULL;
newNode->info = num;
newNode->link = NULL;
if (first == NULL)
{
first = newNode;
last = newNode;
}else
{
last->link = newNode;
last = newNode;
}
cin >> num;
}
}
int main()
{
LinkedList list1;
list1.buildListForward();
cout << " Printing the list" << endl;
list1.print();
return 0;
}