This code is for a linked list.
#include <iostream>
using namespace std;
class Node
{
public:
int value;
Node* next;
};
// This function will print each node values
void printValues(Node *p)
{
int i = 1;
while(p !=NULL)
{
cout << "This is the " << i << " th time " << p->value << "\n\n";
p = p->next;
i++;
}
}
void addNode (Node *p, int newValue)
{
Node *newNode = new Node();
newNode -> value = newValue;
newNode -> next = p;
p = newNode;
}
int main()
{
Node *head = new Node();
Node *second = new Node();
Node *third = new Node();
Node *fourth = new Node();
Node* fifth = new Node();
head -> value = 25;
head ->next = second;
second-> value = 5;
second->next = third;
third ->value = 35;
third -> next = fourth;
fourth ->value = 5;
fourth ->next = fifth;
fifth -> value = 18;
fifth ->next = NULL;
printValues(head);
addNode(head, 32000);
printValues(head);
return 0;
}
This code contains basic function that will print and add a node in front of the pre-existing nodes.
My question is, why is the node not added?
I tried to print it, but it is not printing. Either the node is not added, or I could not make it print.
I made this function to add a new node. This function takes 2 parameters, one is a pointer of the head from the main function, and will keep going to the next value. I have allocated memory for the new node inside this function.
I tried to use the reference to the new node to bring it out of the scope, as the result keeps saying newNode is not found in the main function. I thought it is out of the scope.
I tried double **p and it works fine.
My question is, head is already storing the address, so why pass the head from the main function to this one as a reference? Why make pointer to a pointer when we can just pass head without doing &head?