How can I create a list in C++? I need it to create a linked list. How would I go about doing that? Are there good tutorials or examples I could follow?
There is no such thing as a list in C.
What is Linked List in C? A Linked List is a linear data structure. Every linked list has two parts, the data section and the address section that holds the address of the next element in the list, which is called a node.
That's what an array is. The C programming language doesn't define anything called a list.
To create an array, define the data type (like int ) and specify the name of the array followed by square brackets []. To insert values to it, use a comma-separated list, inside curly braces: int myNumbers[] = {25, 50, 75, 100};
I take it that you know that C++ already has a linked list class, and you want to implement your own because you want to learn how to do it.
First, read Why do we use arrays instead of other data structures? , which contains a good answer of basic data-structures. Then think about how to model them in C++:
struct Node { int data; Node * next; };
Basically that's all you need to implement a list! (a very simple one). Yet it has no abstractions, you have to link the items per hand:
Node a={1}, b={20, &a}, c={35, &b} d={42, &c};
Now, you have have a linked list of nodes, all allocated on the stack:
d -> c -> b -> a 42 35 20 1
Next step is to write a wrapper class List
that points to the start node, and allows to add nodes as needed, keeping track of the head of the list (the following is very simplified):
class List { struct Node { int data; Node * next; }; Node * head; public: List() { head = NULL; } ~List() { while(head != NULL) { Node * n = head->next; delete head; head = n; } } void add(int value) { Node * n = new Node; n->data = value; n->next = head; head = n; } // ... };
Next step is to make the List a template, so that you can stuff other values (not only integers).
If you are familiar with smart pointers, you can then replace the raw pointers used with smart pointers. Often i find people recommend smart pointers to starters. But in my opinion you should first understand why you need smart pointers, and then use them. But that requires that you need first understand raw pointers. Otherwise, you use some magic tool, without knowing why you need it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With