3 ms·
Proposal: Convert the linked list to an indexed structure with dynamic capacity like a vector or a hash table. This is easy to do in one pass. ("Visit the node
by thaumasiotes 8y ago
Proposal:
Convert the linked list to an indexed structure with dynamic capacity like a vector or a hash table. This is easy to do in one pass. ("Visit the node; add it to the hash table. Visit the next node...")
Once you're done, access the middle element.
You've reduced the number of passes from 1.5 to 1, and all it took was duplicating the entire input.
- sethammons 8y agoWhich could be ok depending on memory constraints
- thaumasiotes 8y agoWell, it's ok based on this statement of the problem. It's never going to make sense as an approach in reality, because the work you need to do constructing the second data structure is considerably more than the work you'd need to do to make the extra half pass through the linked list. You're losing on space and time by doing it this way.