I’ve seen a few topics about linked lists, and I’ve read enough to glean how to do it generally, but I want to make sure I’m not wrongly interpreting the information I’ve gathered.
Let’s say I have:
struct element
{
int val;
element *next;
};
The element *next is a pointer to an element, which will be used to connect the elements together in order to form the linked list.
I’ve also gathered that you need to have some kind of “tie off” so you don’t lose your list. My professor describes it as a trail of balloons, and if you dont have a “tie off” your list can get lost.
So I start off with creating the “tie off” pointer:
element first;
first -> *next = 0; // or null
This is where I get lost… How do I add to the head of a linked list? Ordering it isn’t important at this point, I just need to start with an unordered list, I’ll get more complicated later.
Something like this?
element addMe;
addMe -> val = 100;
first -> next = *addMe;
Is that right?
What would I do to add something to a non-empty list?
Thanks for the time!
Edit: This is not homework. We have gone over linked lists, and have done an assignment with them. I did not get a very good grade on the assignment, so I am trying to strengthen my understanding before the next assignment. We will use linked lists again.
Edit2: Thanks!
I do not know if this would be considered “homework” or not. I personally do not think it is, considering I will not be using the code I posted here.
With singly-linked lists, the efficient way to add new elements is putting them at the beginning of the list. For your design, this would be:
You’ll notice that
newHeadis now the first element, andlistno longer represents the whole list. This leads to a more functional programming style, where you are creating new lists all the time (see: theconsfunction in Lisp).Procedural languages like C++ generally use some wrapper structure like this:
so list prepends are expressed as changing an existing list instead of creating a new one.
With such an auxiliary structure, it is also trival to keep track of the list size, and keep a pointer to the last element for fast appends. These both come at the cost of a few extra instructions for every list operation.