Ultra basic Link List trouble

I am trying to remember how to build a basic linked list, it has been a while since my data structures course.

I feel like im pretty close with this code, but its not displaying anything when I run the code other than to take the users input.

Can anyone tell me where I went wrong?

Thank you.


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
#include <iostream>
using namespace std;

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

void addToHead(Node*head);

void displayList(Node*head);

int main()
{
	Node *head;
	head = NULL;
	addToHead(head);
	displayList(head);
return 0;
}

void addToHead(Node *head)
{
	
	int num = 0;
	
	while(num != -1)
	{
		Node *temp = new Node;

		cout << "enter numbers: ";
		cin >> num;

		temp->data = num;
		temp->next = head;
		head = temp;

	}
}

void displayList(Node*head)
{
	Node *tmp;
	tmp = head;

	while(tmp != NULL)
	{
		cout << ":" << tmp->data;
		tmp = tmp->next;
	}

}
After calling addToHead object head in main will be equal to NULL as before because it was passed to the function by value.
Oh I see, the code is referencing the original head so its always seeing a NULL value. Thank you, I will try and re-do this.

I got it working if I do not use the displayList function, but how can I use function to display the list without messing it up?

this works

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>
using namespace std;

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

void addToHead(Node*head);

int main()
{
	Node *head;
	head = NULL;
	addToHead(head);


return 0;
}

void addToHead(Node *head)
{
	
	int num = 0;
	
	while(true)
	{
		Node *temp = new Node;

		cout << "enter numbers: ";
		cin >> num;

		if(num == -1)
			break;

		temp->data = num;
		temp->next = head;
		head = temp;

	}	

	Node *tmp;
	tmp = head;

	while(tmp != NULL)
	{
		cout << ":" << tmp->data;
		tmp = tmp->next;
	}

}
Last edited on
You could declare the function as

void addToHead(Node **head);

and call it as

addToHead(&head);


Of cource you need also to change the body of the function.
Topic archived. No new replies allowed.