0

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?

  • 1
    When you write `p = newNode;` you are changing `p` in the `addNode` function, you are **not** changing `head` in the `main` function. That's why your code doesn't work, using a double pointer it one way to solve this problem, but **returning** the new node is the better way. `head = addNode(head, 32000);` in `main` and `return newNode;` in your `addNode` function. – john Nov 19 '22 at 07:53
  • Linked list problems are the main asked topic on SO C++, so you look for those first. If this code is not for an assignment you should use std::list instead. – Pepijn Kramer Nov 19 '22 at 08:04
  • I think I got the answer to my question now. I think I needed to pass the address of the head so I could receive the address of the pointer of the head. **p or I could just do the pass-by reference and do *&p as the argument of the function. – Niranjan Gaire Nov 22 '22 at 04:02

0 Answers0