Problem with constructors

In the following code, what does it mean to put node*q=0; .
I mean node constructor requires two parameters right?

Also please explain how the code works.Ty!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <iostream>
using namespace std;

class node
{
	public:
		node(int d, node* p=0): data(d), next(p){}
		int data;
		node* next;
};

int main()
{
	int n;
	node* p;
	node*q=0;
	while (cin>>n)
	{
		p = new node(n,q);
		q=p;
	}
	
	for (; p->next; p=p->next)
	cout<< p->data <<"->";
	cout<<"*\n";
        return 0;

}
Node* p = 0 is assign p = NULL. It will help link list have a stop point is NULL.
When p = new node(n,q) then it create a new node with data = x ,next = NULL, and p pointing a new address that node store on memory. When q = p then q have address pointer p.
Sorry, my english is not good
Though itsn't very clear..Ty for the answer!
"I mean node constructor requires two parameters right?"

Yes.

It's called a linked list, a storage technique where certain data is stored in one object together with a pointer to another object of the same data type.

The stored data in your example is just an integer number entered by the user but could be anything.

Works like this;

- new node creates a new node object on the heap, the 1st one in the list.
- the pointer to this object is kept in q for later storage.
- when new node is executed the 2nd time q is passed to the constructor and
stored INSIDE the 2nd object
-This process can be repeated 'indefinitely'

To acces the very first object from let's say the 25th, you just need to roll back the pointers inside the objects. Done in the for loop.


Topic archived. No new replies allowed.