displaying data from structure

Am trying to learn linked lists in c++ but I have failed to display what I enter in the linked list
can anyone help me find what am missing out please.

here is the code below

#include<iostream>

using namespace std;

struct node
{
int num;
node*n_ext;
};
node*nodes=NULL;
int main()
{
for(int i=10;i!=0;)
{
node*p_node=new node;
cin>>i;
p_node->num=i;
p_node->n_ext=nodes;
nodes=p_node;
}

node*p_current_node=nodes;
if(p_current_node!=NULL)
{
cout<<p_current_node->num<<"\n";
p_current_node=p_current_node->n_ext;
}

}
Last edited on
I thnk I have seen the problem i used if statement that is not used in looping
The problem is this:
1
2
3
4
5
if(p_current_node!=NULL) // Replace if with while
{
cout<<p_current_node->num<<"\n";
p_current_node=p_current_node->n_ext;
}


The if needs to be a while.
Try this :
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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
#include <iostream>
#include <fstream>

using namespace std;

struct node
{
	node() : n_ext(NULL), num (0) {}
	int num;
	node * n_ext;
};

void add_node(node*& p_head, node *_node)
{
    node* my_node = p_head;
	if(_node == NULL) return;
    if(my_node == NULL) {p_head = _node; return;}
    while(my_node->n_ext != NULL){my_node = my_node->n_ext;}
	
	my_node->n_ext = _node;
}

void print_node(node* p_head)
{
    node* my_node = p_head;
    if(my_node == NULL) return;
  	cout << my_node->num << endl;

	while(my_node->n_ext != NULL)
	{
		my_node = my_node->n_ext;
		cout << my_node->num << endl;
	}	
}


node* nodes = NULL;

int main()
{
	for(int i = 0;i != 10;)
	{
		node* p_node = new node();
		cout << "Enter i (10 to exit) : ";
		cin >> i;
		p_node->num = i;
		add_node(nodes, p_node);
	}

	cout << "The content of the list : " << endl;
    print_node(nodes);
} 
Is that what you want?
Does that help you? :)
Oh, it helped you.

Glad it helped :)
Topic archived. No new replies allowed.