Nodes in Linked Lists

So I created a bunch of nodes and I made each one before one another. Im having trouble adding another node to the last one.
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
69
70
 
#include <iostream>
using namespace std;

struct nodeType{
	int info;
	nodeType *link;
};

void printList(nodeType *head)
{
	nodeType *current = head;

	if (head == NULL)
	{
		cout << "Empty list\n";
	}
	else{

		while (current != NULL)
		{
			cout << current->info << "  ";
			current = current->link;
		}
		cout << endl;
	}
}
int main()
{
	nodeType *head = NULL; // 1
	nodeType *current;

	printList(head);

	// 2: insert number 100 to  as first node
	current = new nodeType;
	current->info = 100;
	current->link = NULL;
	head = current;
	printList(head);

	// 3: insert number 200 before number 100
	current = new nodeType;
	current->info = 200;
	current->link = head;
	head = current;


	// 4: print link list from the beginning 
	//print the link list
	//-------------------------
	printList(head);
	
	current = new nodeType;
	current->info=300;
	current->link = head;
	head = current;
	
	printList(head);
	
	current = new nodeType;
	current->info=400;
	current->link = NULL;
	head = current;
	
    printList(head);
	system("pause");
	return 0;
}


The node with the value of 400 is the node that has to be last.. How would that work?
Last edited on
I suggest that you make functions like push_front and push_back.

push_front is what are you doing now (insert at head).

push_back is similar to printList, but you need to add the node to current->link and if (head == NULL) -> like the first node (100)

Make sure that the link member of nodeType is always set to nullptr in the first place. The easiest would be a constructor for nodeType
Can you show me an example please? Thanks
Hi Forum, It is very nice discussion about the linked list
for more information refer http://www.cpptutorials.com/2015/01/reversing-linked-list-in-cc-with.html
Topic archived. No new replies allowed.