Suppode we have a linked list in C#, say
LinkedList<int> LList = new LinkedList<int>({1, 2, 3, 4, 5, 6});
A key characteristic of a linked list as a data structure is that we don't have direct access to the i-th element like we do with an array.
But when we access LList.Last
, I assume that C# already has the address of the last element, so that it doesn't have to go through the whole list.
Is this actually the case? Where can I confirm this information?
I've tried to look in the documentation, but I couldn't find anything in this level of detail.
From the documentation:
Retrieving the value of this property is an O(1) operation.
While it doesn't say exactly how it is implemented, the fast that it's an O(1) operation strongly suggests that there's a pointer directly to the last element (or at least some way to reference the last node without traversal).
The documentation for LinkedList
itself states that it's a "doubly-linked list", meaning that each node has a pointer to the next and previous nodes, so a reference to the last node is trivial:
var lastNode = this.Head.Prev; // this.Head points to the "first" node