It's to do really with placement of the first node, depending on whether we have an empty list or not.
The right-hand assignment is done first.
If root is non-null then there is an existing list and the (current) tail->next pointer is set to point to a new node. In the one-off case that root is null then the list is currently empty and we have to set root to the new node.
After all these shenanigans the left-hand assignment is done and the tail pointer is set to point to the newly-assigned node.
It has probably been abbreviated beyond utility, I admit. I usually do linked-list assignment with several more easy-to-read if blocks. The assembled code probably looks the same.
To be fair, I think I pinched the idea from
@dutch at some point - just can't remember where. It was one of his single-line statements that left me in awe.
If you don't mind the reversed order in a forward list then you can construct more easily by adding at the start instead and ditch the tail pointer.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
|
#include <iostream>
#include <fstream>
using namespace std;
struct node
{
string id, name;
node *next;
};
void print( node *n )
{
for ( ; n; n = n->next ) cout << n->id << ' ' << n->name << '\n';
}
int main()
{
ifstream in( "user.txt" );
node *root = nullptr;
for ( string id, name; in >> id && getline( in, name ); root = new node{ id, name, root } );
print( root );
}
| |
Entries come out in reverse order:
144 Mia
121 Maria
112 Sofia
111 David
110 John
100 Mary |
though you can fix that by changing the print() function:
1 2 3 4 5 6 7 8
|
void print( node *n )
{
if ( n )
{
print( n->next );
cout << n->id << ' ' << n->name << '\n';
}
}
| |
to give
100 Mary
110 John
111 David
112 Sofia
121 Maria
144 Mia |