Original Post
I have just recently learned about linked lists and have started to write a linked-list class but I have a simple question about adding nodes.
First, here is the code (not long):
#include <iostream>
#include <cstdlib>
using namespace std;
//Simple node struct
struct Node
{
char name[20];
int age;
Node *next;
};
///////////////////////////////////////////////////////
//Linked list class
class List
{
public:
List(): head(NULL) {};
void PrintList();
void AddNode(char *name,int age);
private:
Node *head; //Head of list
};
///////////////////////////////////////////////////////
//Traverses through list and
//prints out each node''s data
void List::PrintList()
{
Node *temp;
temp = head;
int count = 1; //To count number of nodes
while (temp->next != NULL)
{
cout <<"Node " <<count++ <<endl;
cout <<"Name : " <<temp->name <<endl;
cout <<"Age : " <<temp->age <<endl;
temp = temp->next;
}
//Print out last node
cout <<"Node " <<count <<endl;
cout <<"Name : " <<temp->name <<endl;
cout <<"Age : " <<temp->age <<endl;
} //End PrintList
///////////////////////////////////////////////////////
//Adds a new node to the end of the list
void List::AddNode(char *name,int age)
{
Node *temp = head; //The searching node
//Create new node
Node *newNode = new Node; //<--- HERE IS MY PROBLEM!
strcpy(newNode->name,name);
newNode->age = age;
newNode->next = NULL; //Set the new node as the end of list
//First check if it''s an empty list
if (temp == NULL)
temp->next = newNode;
//Otherwise traverse through list until end
else
{
while (temp->next != NULL)
temp = temp->next;
}
//Chain the previous node with new one
temp->next = newNode;
} //End AddNode
///////////////////////////////////////////////////////
int main()
{
List list;
list.AddNode("Hagga",15);
list.AddNode("Hermy",14);
list.PrintList();
system("PAUSE");
return 0;
}
///////////////////////////////////////////////////////
This line is my problem: (in the AddNode method)
Node *newNode = new Node;
Will the object pointed to by newNode be destroyed after the AddNode method terminates?? (because it was declared locally) And so causing a "memory leak" in the list or something?
If so, then how would I go about creating new nodes in my list (using the keyboard "new"), so that they exist for the whole program?
Thanks for your time