Linked list not listing all nodes...

I have been sitting with this code for a while now and I can't seem to understand what to do to get my printList function to actually list ALL the nodes that I've put into the list. It will only display the last one that've been entered.

I tried to search the forums but I didn't find anything that was very helpful to this particlar situation, maybe didn't look well enough.

Yes... I'm quite new to this so bare with me if you see some obvious fails..


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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
#include <iostream>
#include <string>
using namespace std;


struct node
{
	string firstName;
	string lastName;
	int memberNumber;
	struct node* next;
};
struct node* head = NULL;

void add_node();
void printList();

int main()
{
	int x = 1;
	while(true)
	{
		cout << "Enter person info or '0' to quit"<< endl;
		cin >> x;
		if(x == 0)
			break;
		add_node();
	}
	printList();
	system("pause");
    return 0;
}

//Add node function
void add_node()
{
	node* current;
	
	current = new node;
	if(head == NULL)
	{
		head = current;
	}
	else
	{
		current->next = head;
		head = current;

	}
	cout << "Enter first name: ";
	cin >> current->firstName;
	cout << "Enter last name: ";
	cin >> current->lastName;
	cout << "Enter member number : ";
	cin >> current->memberNumber;
	current->next = NULL;
}

void printList()
{
	node *current = head;
	while(current != NULL)
	{
		cout << "#" <<current->memberNumber <<" - "<< current->firstName << " " << current->lastName <<endl;
		current = current->next;
	}

}

Last edited on
Your list always consists from one element. Consider this code

1
2
3
4
5
6
7
8
	else
	{
		current->next = head;
		head = current;

	}
	// these statements are skipped
	current->next = NULL;


You set current->next (current is always equivalent to head due to the statement head = current;) to NULL. So there is only one element head.
Last edited on
Okay I removed the highlighted line all together and now it actually prints as many elements as i put in. however when I print them a windows pops up in visual studio 2010 saying:

An unhandled exception of type 'System.AccessViolationException' occurred in Programname.exe

Additional information: Attempted to read or write protected memory. This is often an indication that other memory is corrupt.

why is that?
Last edited on
why is that?


Because you're accessing memory you shouldn't. By removing current->next = NULL you created another problem.
Topic archived. No new replies allowed.