niksrb niksrb - 1 month ago 6
C++ Question

Pointer to the element in the list VS element itself

I have found this code on the internet and I need a little help with it.
Here's the code:

#include<iostream>
using namespace std;

/* Linked list structure */
struct list {
struct list *prev;
int data;
struct list *next;
} *node = NULL, *first = NULL, *last = NULL, *node1 = NULL, *node2 = NULL;

class linkedlist {
public:

/* Function for create/insert node at the beginning of Linked list */
void insert_beginning() {
list *addBeg = new list;
cout << "Enter value for the node:" << endl;
cin >> addBeg->data;
if(first == NULL) {
addBeg->prev = NULL;
addBeg->next = NULL;
first = addBeg;
last = addBeg;
cout << "Linked list Created!" << endl;
}


else {
addBeg->prev = NULL;
first->prev = addBeg;
addBeg->next = first;
first = addBeg;
cout << "Data Inserted at the beginning of the Linked list!" << endl;
}
}


What I don't understand is when he is making the new Node object (in this case it's addBeg) he is putting a pointer operator in front of it. And how I'm seeing it now, shouldn't the object be created without the '*' before it's name and with the data, pointer to next and pointer to the previous one, unlike the pointer to the node in the list which should only contain address of the node, without any other data ? If that's not the case, then what is the thing that differs the pointer to the node in the list from the node itself ?

Answer

The way it's been done in the code is correct. You are having an incorrect understanding in that the data of a node cannot be accessed through the pointer to that node.

If addBeg is the pointer pointing to the node returned by new list, then the data of that node can be accessed using the operator ->:

list.data is equivalent to addBeg->data.

If that's not the case, then what is the thing that differs the pointer to the node in the list from the node itself ?

=> addBeg is the pointer pointing to an object, that object being returned by new List.