Forward-Link Lists and Inserting Elements

closed account (3w5ihbRD)
This is some code I drew from the C++ Crash Course by Josh Lospinoso I'm using to teach myself c++.


Please correct me if I'm wrong, but it seems that an Element Object called "new_element" was created when he created a pointer called "new_element.

Where I'm mostly confused is at the line of code "new_element->next = next;"
What's really going on here? I know that the "next" pointer of trooper1 will be pointing to the "next" pointer (or is this the base address of trooper2 which happens to be where its "next" pointer lives) of trooper2. I just can't see how this is happening.

Thank you for your help in understanding this.

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
struct Element {
	Element* next{};

	void insert_after(Element* new_element) {
		new_element->next = next;
		next = new_element;
  	}

	char prefix[2];
	short operating_number;
};

int main() {
	Element trooper1, trooper2, trooper3;
	trooper1.prefix[0] = 'T';
	trooper1.prefix[1] = 'K';
	trooper1.operating_number = 421;
	trooper1.insert_after(&trooper2);
	trooper2.prefix[0] = 'F';
	trooper2.prefix[1] = 'N';
	trooper2.operating_number = 2187;
	trooper2.insert_after(&trooper3);
	trooper3.prefix[0] = 'L';
	trooper3.prefix[1] = 'S';
	trooper3.operating_number = 005;

	for (Element* cursor = &trooper1; cursor; cursor = cursor->next) {
		printf("Storm Trooper %c%c-%d\n", cursor->prefix[0], cursor->prefix[1], cursor->operating_number);
	}
}
Last edited on
At initializing time next does not point to anything (= nullptr). Line 18 basically appends trooper2 after trooper1. trooper2->next points to whatever trooper1->next pointed to. In this case nullptr. trooper1->next will now point to trooper2.

Line 22 will be similar.
closed account (3w5ihbRD)
Okay. So it's like the pointer of trooper2 picks up where the pointer of trooper1 left off, so that pointer of trooper1 can be released to point to trooper2?

Why does it have to be released? In other words why can't we eliminate line 5 and jump straight to line 6 especially if trooper1->next and trooper2->next both don't point to anything?

Since the arrow operator dereferencesnew_element and allows it access to the contents of trooper2 and enables it to edit those contents, we're able to say

trooper2->next?

Thank you for clarifying.

Last edited on
In other words why can't we eliminate line 5 and jump straight to line 6 especially if trooper1->next and trooper2->next both don't point to anything?
Well, if you remove line 5 it wouldn't be an insert anymore.

However you can do this (line 18 etc.):

trooper1.next = &trooper2;

At that point you know that you don't need an insert.


we're able to say

trooper2->next?
No, trooper2 isn't a pointer. next is. Thus it would look like:

trooper2.next->operating_number

The result would be the operating_number of trooper3 (if done after line 25).
Topic archived. No new replies allowed.