I'm looking at some interview questions, and one of them asks to reverse a linked list that contains a cycle. So suppose I had a linked list like the following:
F <- E
| /\
V |
A -> B -> C -> D
Then reversing the list would create the following:
F -> E
/\ |
| V
A <- B <- C <- D
The problem here is that there's a conflict between which nodes C should be pointing at. So would we just eliminate the link between C and F?
Mathematically, you can think of a linked list (possibly containing a cycle) as a partial function from a set of nodes into itself, where each node maps to its successor and every node is eventually reachable from the start node. (The last node has no successor). Reversing a linked list would then entail inverting this function, since following a link and then going backwards across it should end you up back where you started.
If the linked list does not contain a cycle, then this partial function is injective (one-to-one), meaning that no two nodes map to the same successor. Injective functions can indeed be inverted, which is why you can reverse a regular linked list. However, if the list contains a cycle (and isn’t just one large cycle), then there are two nodes with the same successor, so the function is not injective and thus does not have an inverse. So no, you cannot reverse the linked list and expect to get another linked list, if the list has a cycle.
However, if you treat the linked list as a more general graph in which each node can have any number of incoming or outgoing edges, then the inverse does exist. It's just not a linked list anymore.
The original list would be AB CDEF CDEF CDEF ...
To reverse that you'd need a linked list that generates FEDC
an infinite number of times followed by BA
, so I'd say no, there's no way to build a linked list that would generate that sequence.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With