I trying to get the hang of link list, but very time a write one i fail miserably...

struct node
{
	int data;
	node *next;
};

int main()
{
	node *head = new node;
	head = NULL;
	node *temp = head;

	//node 1
	temp->data = 1;
	temp->next = NULL;
	temp = temp->next; 

	//node 2
	temp->data = 2;
	temp->next = NULL;

	//traverse
	temp = head;
	while(temp != NULL)
	{
		cout << temp->data;
		temp = temp->next;
	}
   
   return 0;
}

please tell me what i'm doing wrong.

Recommended Answers

node *head = new node();

...then after calling new, you're setting it to
NULL.

Jump to Post

Keep in mind: what you're trying to do is create a chain with a dead-end.
You can do that by creating a number of objects up-front or by creating a dynamic list that has a dead-end.
Each dead-end becomes a new link when you call new node() on it.

Jump to Post

All 5 Replies

node *head = new node();

...then after calling new, you're setting it to
NULL.

node *head = new node();

...then after calling new, you're setting it to
NULL.

i removed that part of the code, but it still says the error is when i make temp->data = 1; in the first node.

Keep in mind: what you're trying to do is create a chain with a dead-end.
You can do that by creating a number of objects up-front or by creating a dynamic list that has a dead-end.
Each dead-end becomes a new link when you call new node() on it.

You can even make it circular by changing the node address of the dead-end to be the first node.

simple:

int main()
{
	node *head = new node;
	//head = NULL;
	node *temp = head;

	//node 1
	temp->data = 1;
	temp = temp->next;// temp->next is null;

	//node 2
	temp = new node;
	temp->data = 2;
	temp->next = NULL;

	//traverse
	temp = head;
	while(temp != NULL)
	{
		cout << temp->data;
		temp = temp->next;
	}
   
   return 0;
}

Ok thanks, i think i have the hang of it.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of 1.20 million developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.