Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to reverse a linked list that contains a cycle?

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?

like image 968
Sam Avatar asked Mar 06 '11 09:03

Sam


2 Answers

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.

like image 94
templatetypedef Avatar answered Oct 22 '22 16:10

templatetypedef


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.

like image 36
Brad Mace Avatar answered Oct 22 '22 16:10

Brad Mace