Reputation:
If I have structure: /* 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 is the SYNTAX difference between creating a new node (with 2 pointers and data) and just a single pointer apart from node, to use in same program. (Difference between bolded parts)
Upvotes: 1
Views: 9183
Reputation: 57678
Here are some examples.
Declaring a node
variable
node n;
Here n
is a variable or instance of type node
.
Declaring a pointer to node
type
node * pointer_to_node;
Notice the *
after the type identifier. The *
is used to declare pointers.
Also notice that the pointer is not pointing to anything.
Pointing the Pointer
A pointer can point to anything of its type. So the following is valid:
node n;
node * pointer_to_node = &n;
In the above example, the pointer_to_node
is initialized to point to the variable n
.
node * pointer_to_dynamic = new node;
In the above statement, the program allocates a node
instance in dynamic memory. The location of the memory is assigned to the pointer_to_dynamic
variable. In other words, the variable pointer_to_dynamic
now points to the newly allocated dynamic memory.
Upvotes: 2