Hello. I am studying this sample code for linked list class node implementation.
I've studied this code for hours and I am not 100% sure how this code keeps track of the head node.
Here;s what I know so far, and if you want to add/correct anything feel free to do so:
class Node
{
public:
Node(); // constructor of class node without arguments
Node(int, Node*); //constructor with arguments of int type and a pointer node type
Node* next() const;
void setNext(Node*); //member fun, returning a pointer of node type
void setKey(int);
int getKey() const;
int done;
private:
Node* ptr;
int key;
};
Node::Node() // constructor intialisation
{
ptr = NULL;
key = -1;
done = 1;
}
Node::Node(int tkey, Node* tnode) // intialisation to private members
{
ptr = tnode;
key = tkey;
done = 1;
}
Node* Node::next() const
{
return ptr;
}
int Node::getKey() const // returning the key to be inserted
{
return key;
}
void Node::setNext(Node* tnode) // setting the link to next node in ptr
{
ptr = tnode;
}
void Node::setKey(int tkey) // setting the value to be inserted in key {
key = tkey;
}
void insert(Node* head, int key) // function taking the starting pointer of list and key to be inserted {
Node* temp = new Node(key, NULL); // creating a new node by calling function Node(int, Node*)
Node* index;
if(key < head->getKey()) // comparing the key to be inserted and present starting key of the list
{
index = new Node(key, head); // if true, make the key to be inserted as the starting key
head = index;
return;
}
index = head;
while(index->next()!=NULL && index->next()->getKey() < key) //else traverse the list until key to be inserted is greater than the values in the list.
{
index = index->next(); // when found the place to insert the key, store the pointer in index.
}
temp->setNext(index->next()); // point temp->link to index.
index->setNext(temp);
return;
}
void printList(Node * head) // print the list, starting form head of the list
{
Node* index = head; // storing value head in pointer index
cout << index->getKey() << ", ";
while(index->next()!= NULL) //till the end of list or index->next is not equal to NULL
{
index = index->next(); //traversing node by node
cout << index->getKey() << ", ";
}
cout << "\n";
It looks like you commented the code pretty well, I am not sure how you're confused. Which objects are you concerned about, or which lines still confuse you?
Oh. Is this the reason why in Node::Node(), ptr is NULL? Since this is first node, its pointer is null because it's not pointing to anything. Is this right?