Populating a linked list

Hi,

Basic question.
I'm trying to rekindle my C++ skills and I'm working through online problems.
I came across one on linked lists and realised I don't remember as much about them as I thought I did.

I'm mucking around with basic linked programs but all online examples I see appear to have fixed number of members.
What if I want to create an empty list and fill it with a large number of items?

Below is one of the examples I am working on.
But instead of "head", "second" and "third" I want to start with an empty list and use some kind of loop to populate the list.

Just struggling to get my head around it.

Any help would be appreciated.

Thanks.
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
#include <iostream>

using namespace std;

class Node
{
public:
    int Value;
    Node* Next;
};

void printList(Node* n)
{
    while()
    {
        cout << n->Value << endl;
        n = n->Next;
    }

}

int main()
{
    Node* head = new Node();
    Node* second = new Node();
    Node* third = new Node();

    head->Value = 1;
    head->Next = second;
    second->Value = 2;
    second->Next = third;
    third->Value = 3;
    third->Next = NULL;

    printList(head);

    return 0;
}
Last edited on
1
2
3
4
5
6
7
8
9
Node *head = nullptr;
int count;
std::cin >> count;
while (count--){
    auto node = new Node;
    node->Value = count;
    node->Next = head;
    head = node;
}
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>

class MyList1 {
public:
	MyList1() {}
	~MyList1();
	MyList1(const MyList1&) = delete;
	MyList1& operator=(const MyList1&) = delete;

	void insertAtFront(int dat);
	void Display() const;

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

	Node* head {};
};

MyList1::~MyList1() {
	while (head) {
		const auto cur {head};

		head = head->next;
		delete cur;
	}
}

void MyList1::insertAtFront(int dat) {

	head = new Node(dat, head);
}

void MyList1::Display() const {

	for (auto cur {head}; cur; cur = cur->next)
		std::cout << cur->data << '\n';

	std::cout << '\n';
}

int main() {
	MyList1 ml;

	int num {};

	while ((std::cout << "Enter a number (-999 to end): ") && (std::cin >> num) && num != -999)
		ml.insertAtFront(num);

	ml.Display();
}

Last edited on
Thanks, I'll give those a try.
Registered users can post here. Sign in or register to post.