1

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)

6
  • 1
    I can not understand what you are asking. Could you maybe include examples of both alternatives that you have in mind? Commented Oct 24, 2016 at 15:25
  • 6
    Google "so c++ book list". Commented Oct 24, 2016 at 15:26
  • What do you mean by syntax difference? You would have a pointer to the prev node and next node to be able to move forwards and backwards in your linked list or whatever data structure you have. It just depends on what you are designing Commented Oct 24, 2016 at 15:26
  • When you say "creating", do you mean on the stack (e.g. int n;) or on the heap (e.g. int *p = new int;)? Commented Oct 24, 2016 at 15:27
  • Are you talking about a doubly-linked list (prev, next) vs singly-linked list(next)? Commented Oct 24, 2016 at 15:30

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments